import asyncio
import subprocess
import logging
from pathlib import Path
import gettext
import izvor_utils as izvor
import os

_ = gettext.gettext


logging.basicConfig(level=logging.DEBUG)

config_template = {
    "path": "~/",
    "min_chars": 3,
    "case_insensitive": True,
    "limit": 16,
    "enable_search": True,
    "enable_path": True
}

class Provider(izvor.Provider):
    def __init__(self, config: dict):
        super().__init__(
                name=_("Files"),
                icon="system-file-manager",
                description=_("Search for files and directories on your device."),
                config=config
        )

    async def search(self, query: str):
        if len(query) < self.config["min_chars"]:
            return

        if self.config["enable_path"] and query.startswith("/") or query.startswith("~/"):
            # Provide an entry to open the entered path
            def execute():
                izvor.xdg_open(str(Path(query).expanduser().resolve()))

            yield {
                "name": _("Open in file manager"),
                "description": str(Path(query).expanduser().resolve()),
                "image": ("logo", "system-file-manager"),
                "execute": execute
            }

        command = ["locate", query,
            "-r", str(Path(self.config["path"]).expanduser().resolve()) + "/*",
            "-i" if self.config["case_insensitive"] else ""]

        if self.config["limit"] > 0:
            command.extend(["-l", str(self.config["limit"])])

        if os.getenv("FLATPAK_SANDBOX_DIR"):
            command = ["flatpak-spawn", "--host"] + command

        process = await asyncio.create_subprocess_exec(
            *command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        stdout, stderr = await process.communicate()

        if process.returncode != 0:
            logging.error(f"Cannot locate files: {stderr.decode().strip()}")
            return

        for line in stdout.decode().splitlines():
            file_path = Path(line.strip())

            if not file_path.exists() or not (file_path.is_file() or file_path.is_dir()):
                continue

            def execute(file_path=file_path):
                izvor.xdg_open(str(file_path))

            yield {
                "name": file_path.name,
                "description": str(file_path),
                "image": ("logo", "system-file-manager"),
                "execute": execute
            }
