# -*- coding: utf-8 -*-
# Insync Thunar Plugin
#
# Authors
# Brett Hartshorn <brett@insynchq.com>
# Luis Manuel R. Pugoy <lpugoy@insynchq.com>
#
# Copyright Insynchq Pte. Ltd., ("Insync") | http://www.insynchq.com
# License: GNU GPL v2

DEV_MODE = False

import json
import os
import socket
import sys

try:
    from urllib import unquote  # Python 2.X
except ImportError:
    from urllib.parse import unquote  # Python 3+

try:
    from importlib import reload  # Python 3.4+
except ImportError:
    from imp import reload  # Python 2.x-3.3

from gi.repository import GObject, Gtk, Thunarx  # noqa isort:skip

if sys.getdefaultencoding() != "utf-8":
    reload(sys)
    sys.setdefaultencoding("utf-8")  # pylint: disable=E1101


def ipc_insync(**kw):
    # print('<ipc-insync>',kw)
    data = json.dumps(kw)
    socket_file = u"/tmp/insync%r.sock" % os.getuid()
    if not os.path.exists(socket_file):
        if DEV_MODE:
            print("WARN: insync socket not found")
        return None
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.settimeout(0.1)
    try:
        sock.connect(socket_file)
        sock.send(str.encode(data))
        res = sock.recv(4096)
        sock.close()
    except:
        return None
    if res.strip():
        return json.loads(res.strip())
    else:
        return None


class InsyncPlugin(GObject.GObject, Thunarx.MenuProvider):
    def __init__(self):
        self.file_list = dict()

    def do_action(self, menu, file, method):
        path = unquote(file.get_uri()[len("file://") :])
        ipc_insync(method=method, full_path=path)

    def get_file_menu_items(self, window, files):
        if DEV_MODE:
            print("get file items", files)

        if len(files) != 1:
            # TODO what can we do with mutiple files here
            return None

        file = files[0]
        if file.get_uri_scheme() != "file":
            return None

        path = os.path.realpath(unquote(file.get_uri()[len("file://") :]))
        if sys.version_info[0] < 3:
            path = unicode(path)  # noqa
        else:
            path = str(path)
        if DEV_MODE:
            print(path)
        is_dir = os.path.isdir(path)

        cm_info = ipc_insync(command="CONTEXT-MENU-ITEMS", full_path=path)

        if cm_info:
            title, cm_items = cm_info
            tooltip = "Insync folder actions" if is_dir else "Insync file actions"
            item = Thunarx.MenuItem(
                name="Insync:" + title,
                label=title,
                tooltip=tooltip,
                icon=Gtk.STOCK_FILE,
            )
            sub_menu = Thunarx.Menu()
            item.set_menu(sub_menu)

            item_id = 0
            for text, cmd in cm_items:
                if text == "separator":
                    text = u"\u2015" * 10
                    name = "Insync:separator:" + str(item_id)
                else:
                    name = "Insync::%d" % (item_id)
                item_id += 1
                menu_item = Thunarx.MenuItem(name=name, label=text, tooltip=text)
                if cmd:
                    menu_item.connect("activate", self.do_action, file, cmd)
                else:
                    menu_item.sensitive = False
                sub_menu.append_item(menu_item)

            return [item]
        return None
