# -*- coding: utf-8 -*-
# Copyright (c) 2017-2024 Manuel Schneider
# Copyright (c) 2023 Oskar Haarklou Veileborg (@BarrensZeppelin)

import json
import subprocess
from platform import system
from pathlib import Path
from shutil import which

from albert import *

md_iid = "5.0"
md_version = "3.1.2"
md_name = "CopyQ"
md_description = "Access CopyQ clipboard"
md_license = "MIT"
md_url = "https://github.com/albertlauncher/albert-plugin-python-copyq"
md_authors = ["@ManuelSchneid3r", "@BarrensZeppelin"]
md_maintainers = ["@BarrensZeppelin"]
md_platforms = ["Darwin", "Linux"]


copyq_script_getAll = r"""
var result=[];
for ( var i = 0; i < size(); ++i ) {
    var obj = {};
    obj.row = i;
    obj.mimetypes = str(read("?", i)).split("\n");
    obj.mimetypes.pop();
    obj.text = str(read(i));
    result.push(obj);
}
JSON.stringify(result);
"""

copyq_script_getMatches = r"""
var result=[];
var match = "%s";
for ( var i = 0; i < size(); ++i ) {
    if (str(read(i)).search(new RegExp(match, "i")) !== -1) {
        var obj = {};
        obj.row = i;
        obj.mimetypes = str(read("?", i)).split("\n");
        obj.mimetypes.pop();
        obj.text = str(read(i));
        result.push(obj);
    }
}
JSON.stringify(result);
"""


class Plugin(PluginInstance, GeneratorQueryHandler):

    def __init__(self):
        PluginInstance.__init__(self)
        GeneratorQueryHandler.__init__(self)

        if system() == "Darwin":
            hardcoded_executable = Path("/Applications/CopyQ.app/Contents/MacOS/CopyQ")
            self.executable = hardcoded_executable if hardcoded_executable.exists() else None
            self.icon_factory = lambda: Icon.fileType("/Applications/CopyQ.app")
        elif system() == "Linux":
            self.executable = which("copyq")
            self.icon_factory = lambda: Icon.theme("copyq")
        else:
            raise NotImplementedError(f"Unsupported platform: {system()}")

        if not self.executable:
            raise FileNotFoundError("CopyQ executable not found.")

    def defaultTrigger(self):
        return "cp "

    def items(self, ctx):
        items = []
        script = copyq_script_getMatches % ctx.query if ctx.query else copyq_script_getAll
        proc = subprocess.run([self.executable, "-"], input=script.encode(), stdout=subprocess.PIPE)
        json_arr = json.loads(proc.stdout.decode())

        for json_obj in json_arr:
            row = json_obj["row"]
            text = json_obj["text"]
            if not text:
                text = "No text"
            else:
                text = " ".join(filter(None, text.replace("\n", " ").split(" ")))

            act = lambda s=script, r=row: (
                lambda: runDetachedProcess([self.executable, s % r])
            )
            items.append(
                StandardItem(
                    id=self.id(),
                    icon_factory=self.icon_factory,
                    text=text,
                    subtext="%s: %s" % (row, ", ".join(json_obj["mimetypes"])),
                    actions=[
                        Action("paste", "Paste", act("select(%s); sleep(60); paste();")),
                        Action("copy", "Copy", act("select(%s);")),
                        Action("remove", "Remove", act("remove(%s);")),
                    ],
                )
            )

        yield items
