#!/usr/bin/env python3
import gi
import os
import sys
import subprocess

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

sys.path.insert(0, '/Libraries/Python/v3')
from i18n.i18n import init_locale, str_tr

init_locale('/System/i18nStrings/nebide-shellaction')

class EmptyTrash(Gtk.MessageDialog):
    _TRASH_DIR = os.path.expanduser('~/.local/share/Trash/files')
    def __init__(self):
        count = len(os.listdir(self._TRASH_DIR)) if os.path.isdir(self._TRASH_DIR) else 0
        if count == 0:
            subprocess.Popen(['notify-send', str_tr('empty_trash.title'), str_tr('empty_trash.already_empty'), '--icon=user-trash'])
            return
        super().__init__(
            message_type=Gtk.MessageType.QUESTION,
            buttons=Gtk.ButtonsType.NONE,
            text=str_tr('empty_trash.title'),
        )
        self.format_secondary_text(str_tr('empty_trash.confirm') % count)
        self.add_button(str_tr('empty_trash.btn_cancel'), Gtk.ResponseType.CANCEL)
        self.add_button(str_tr('empty_trash.btn_empty'), Gtk.ResponseType.OK)
        self.set_default_response(Gtk.ResponseType.CANCEL)
        response = self.run()
        self.destroy()
        if response == Gtk.ResponseType.OK:
            self.action_EmptyTrash()
        else:
            self.action_Cancel()

    def action_EmptyTrash(self):
        subprocess.Popen(['gio', 'trash', '--empty'])

    def action_Cancel(self):
        subprocess.Popen(['notify-send', str_tr('empty_trash.title'), str_tr('empty_trash.canceled'), '--icon=user-trash-full'])


class WDisplaysWarning(Gtk.MessageDialog):
    def __init__(self):
        super().__init__(
            message_type=Gtk.MessageType.INFO,
            buttons=Gtk.ButtonsType.NONE,
            text=str_tr('wdisplays_warning.title'),
        )
        self.format_secondary_text(str_tr('wdisplays_warning.text'))
        self.add_button(str_tr('wdisplays_warning.btn_close'), Gtk.ResponseType.CLOSE)
        self.add_button(str_tr('wdisplays_warning.btn_cc'), 1)
        self.add_button(str_tr('wdisplays_warning.btn_continue'), 2)
        response = self.run()
        self.destroy()
        if response == 1:
            self.action_OpenCC()
        elif response == 2:
            self.action_Continue()

    def action_OpenCC(self):
        subprocess.Popen(['napp-run', '/Applications/Control Center.napp', '--', 'system.display'])

    def action_Continue(self):
        import shutil
        kanshi_config = os.path.expanduser('~/.config/kanshi/config')
        subprocess.run(['pkill', 'kanshi'])
        while Gtk.events_pending():
            Gtk.main_iteration()
        subprocess.run(['/usr/bin/wdisplays'])
        wlr = subprocess.run(['wlr-randr'], capture_output=True, text=True).stdout
        if os.path.isfile(kanshi_config):
            shutil.copy(kanshi_config, kanshi_config + '.bak')
        current = ''
        enable = ''
        mode = ''
        position = ''
        scale = ''
        transform = ''
        lines_out = ['profile {\n']
        for line in wlr.splitlines():
            if line.startswith(('eDP-', 'HDMI-', 'DP-')):
                if current:
                    lines_out.append(f'    output {current} {enable} {mode} {position} {scale} {transform}\n')
                current = line.split()[0]
                enable = 'disable'
                mode = ''
                position = 'position 0,0'
                scale = 'scale 1'
                transform = 'transform normal'
            elif line.strip() == 'Enabled: yes':
                enable = 'enable'
            elif line.strip() == 'Enabled: no':
                enable = 'disable'
            elif 'Position:' in line:
                position = 'position ' + line.split()[1]
            elif 'Scale:' in line:
                scale = 'scale ' + line.split()[1]
            elif 'Transform:' in line:
                transform = 'transform ' + line.split()[1]
            elif 'current' in line:
                mode = 'mode ' + line.split()[0] + '@' + line.split()[2]
        if current:
            lines_out.append(f'    output {current} {enable} {mode} {position} {scale} {transform}\n')
        lines_out.append('}\n')
        os.makedirs(os.path.dirname(kanshi_config), exist_ok=True)
        with open(kanshi_config, 'w', encoding='utf-8') as f:
            f.writelines(lines_out)
        subprocess.Popen(['kanshi'])


class WCMWarning(Gtk.MessageDialog):
    def __init__(self):
        super().__init__(
            message_type=Gtk.MessageType.INFO,
            buttons=Gtk.ButtonsType.NONE,
            text=str_tr('wcm_warning.title'),
        )
        self.format_secondary_text(str_tr('wcm_warning.text'))
        self.add_button(str_tr('wcm_warning.btn_close'), Gtk.ResponseType.CLOSE)
        self.add_button(str_tr('wcm_warning.btn_cc'), 1)
        self.add_button(str_tr('wcm_warning.btn_continue'), 2)
        response = self.run()
        self.destroy()
        if response == 1:
            self.action_OpenCC()
        elif response == 2:
            self.action_Continue()

    def action_OpenCC(self):
        subprocess.Popen(['napp-run', '/Applications/Control Center.napp'])

    def action_Continue(self):
        subprocess.Popen(['/usr/bin/wcm'])


class TerminalInfo(Gtk.MessageDialog):
    def __init__(self):
        super().__init__(
            message_type=Gtk.MessageType.INFO,
            buttons=Gtk.ButtonsType.NONE,
            text=str_tr('terminal_info.title'),
        )
        self.format_secondary_text(str_tr('terminal_info.text'))
        self.add_button(str_tr('terminal_info.btn_close'), Gtk.ResponseType.CLOSE)
        self.add_button(str_tr('terminal_info.btn_cc'), 1)
        response = self.run()
        self.destroy()
        if response == 1:
            self.action_OpenCC()

    def action_OpenCC(self):
        subprocess.Popen(['napp-run', '/Applications/Control Center.napp', '--', 'custom.bindings'])


class TrashInfo:
    _TRASH_DIR = os.path.expanduser('~/.local/share/Trash/files')
    def __init__(self):
        if not os.path.isdir(self._TRASH_DIR):
            count, items = 0, []
        else:
            entries = os.listdir(self._TRASH_DIR)
            count, items = len(entries), entries[:10]
        if count == 0:
            tooltip = f'<b>{str_tr("empty_trash.tooltip_empty")}</b>'
        else:
            tooltip = f'<b>{str_tr("empty_trash.tooltip_items") % count}</b>'
            for item in items:
                tooltip += '\\n' + item.replace('\\', '\\\\').replace('"', '\\"')
            if count > 10:
                tooltip += '\\n' + (str_tr('empty_trash.tooltip_more') % (count - 10))
        print(f'{{"tooltip": "{tooltip}"}}')


ACTIONS = {
    'empty-trash': EmptyTrash,
    'trash-info': TrashInfo,
    'wdisplays-warning': WDisplaysWarning,
    'wcm-warning': WCMWarning,
    'terminal-info': TerminalInfo,
}


def main():
    if len(sys.argv) < 2 or sys.argv[1] not in ACTIONS:
        print(f"nebide-shellaction: unknown action '{sys.argv[1] if len(sys.argv) > 1 else ''}'", file=sys.stderr)
        print(f"available: {', '.join(ACTIONS)}", file=sys.stderr)
        sys.exit(1)
    ACTIONS[sys.argv[1]]()


if __name__ == '__main__':
    main()
