from gi.repository import GObject

import logging
from typing import NamedTuple, Optional
from urllib.parse import urlparse, parse_qs

from iotas.note import Note


class UriParseResult(NamedTuple):

    success: bool
    note: Optional[Note] = None
    open: bool = False


# Note: Iotas' addition of this URI handler is a stopgap measure until the freedesktop
# intent system is fleshed out. The handling provided here will be unceremoniously removed
# when that system is available and may be removed or modified without notice beforehand;
# this is not a stable public interface.


class UriToNoteCreator(GObject.Object):
    """Handles creation of notes from temporary iotas-notes:// URI."""

    def __init__(self) -> None:
        super().__init__()

    def parse(self, uri: str) -> UriParseResult:
        """Parse URI to note.

        See comment in source re. interface.

        :param str uri: URI
        :return: Result
        :rtype: UriParseResult
        """
        logging.debug(f"Handling {uri}")
        parsed = urlparse(uri)
        if parsed.netloc != "create-note":
            logging.warning(f"Not handling unknown URI '{parsed.netloc}'")
            return UriParseResult(False)

        fields = parse_qs(parsed.query)
        if "content" not in fields or fields["content"][0].strip() == "":
            logging.warning("No content provided, not creating note from URI")
            return UriParseResult(False)
        if "title" not in fields or fields["title"][0].strip() == "":
            logging.warning("No title provided, not creating note from URI")
            return UriParseResult(False)

        note = Note()
        note.content = fields["content"][0]
        note.title = fields["title"][0]
        if "category" in fields and fields["category"][0].strip() != "":
            note.category = fields["category"][0]
        note.flag_changed()

        open = "open" in fields and fields["open"][0] == "1"

        return UriParseResult(True, note, open)
