#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import psutil
import subprocess
import sys
from tkinter import *
from tkinter import messagebox
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

home = os.path.expanduser('~')
lang = os.environ.get('LANGUAGE')
user = os.environ.get('USER')

app = ""
params = ""
icon = ""
tip = ""
e1 = []
e2 = []
e3 = []
e4 = []
filename = home + '/.config/autostart/cmds-to-systray'

def warning(app):
    rc = subprocess.call(['which', app])
    if rc != 0:
        title = subprocess.getoutput('gettext "Error"')
        msg = subprocess.getoutput('gettext "The application \'"') + app + subprocess.getoutput('gettext "\' doesn\'t exist or is not executable!"')
        window = Tk()
        window.wm_withdraw()
        window.geometry("1x1+" + str(window.winfo_screenwidth() // 2) + "+" + str(window.winfo_screenheight() // 2))
        messagebox.showinfo(title, msg)
        sys.exit()

class GetParams:
    def __init__(self):
        global app, params, icon, tip, e1, e2, e3, e4

        if len(sys.argv) > 1:
            app = sys.argv[1]
            if not app:
                sys.exit()
            warning(app)
            if len(sys.argv) > 2:
                params = sys.argv[2]
            if len(sys.argv) > 3:
                icon = sys.argv[3]
            if not icon:
                icon = app
            if len(sys.argv) > 4:
                tip = sys.argv[4]
            else:
                tip = app
        else:
            self.create_gui()

    def create_gui(self):
        global app, params, icon, tip, e1, e2, e3, e4

        applbl = subprocess.getoutput('gettext " Application:   "')
        paramlbl = subprocess.getoutput('gettext " Parameters:  "')
        iconlbl = subprocess.getoutput('gettext " Icon:               "')
        tiplbl = subprocess.getoutput('gettext "Tooltip:         "')

        master = Tk()
        master.title("To System Tray")
        l1 = Label(master, text=applbl).grid(row=0)
        l2 = Label(master, text=paramlbl).grid(row=1)
        l3 = Label(master, text=iconlbl).grid(row=2)
        l4 = Label(master, text=tiplbl).grid(row=3)

        e1 = Entry(master, width=50, borderwidth=5)
        e2 = Entry(master, width=50, borderwidth=5)
        e3 = Entry(master, width=50, borderwidth=5)
        e4 = Entry(master, width=50, borderwidth=5)

        e1.grid(row=0, column=1)
        e2.grid(row=1, column=1)
        e3.grid(row=2, column=1)
        e4.grid(row=3, column=1)

        b = Button(master, text=' OK ', command=master.quit)
        b.grid(row=4, column=0, sticky=W, pady=4)

        master.mainloop()

        app = e1.get()
        if not app:
            sys.exit()
        warning(app)
        params = e2.get()
        icon = e3.get()
        if not icon:
            icon = app
        tip = e4.get()
        if not tip:
            tip = app

        master.destroy()

class SystrayIconApp:
    def __init__(self):
        global icon
        self.tray = Gtk.StatusIcon()
        icon = icon.replace("$HOME", home)
        icon = icon.replace("~", home)
        if "/" not in icon:
            self.tray.set_from_icon_name(icon)
        else:
            self.tray.set_from_file(icon)
        self.tray.connect('activate', self.on_left_click)
        self.tray.connect('popup-menu', self.on_right_click)
        self.tray.set_tooltip_text(tip)

    def on_left_click(self, icon):
        global params
        params = params.replace("$HOME", home)
        params = params.replace("~", home)
        params = params.replace("$USER", user)
        params = params.replace("\"", "'")

        if app not in ["bash", "sh", "ksh", "csh", "tcsh", "zsh", "fish"]:
            if app in (p.name() for p in psutil.process_iter()):
                os.system("killall " + app)
            exitcode = subprocess.Popen([app, params])
        else:
            cmd = app + " " + params
            exitcode = subprocess.Popen(cmd, shell=True, executable=app)

    def on_right_click(self, icon, event_button, event_time):
        self.make_menu(event_button, event_time)

    def make_menu(self, event_button, event_time):
        menu = Gtk.Menu()

        # show about dialog
        about = Gtk.MenuItem(label=subprocess.getoutput('gettext "About"'))
        about.show()
        menu.append(about)
        about.connect('activate', self.show_about_dialog)

        # add permanent item
        permanent = Gtk.MenuItem(label="→ Permanent")
        permanent.show()
        menu.append(permanent)
        permanent.connect('activate', self.make_permanent)

        # add quit permanent item
        quit_permanent = Gtk.MenuItem(label="Quit permanent")
        quit_permanent.show()
        menu.append(quit_permanent)
        quit_permanent.connect('activate', self.quit_permanent)

        # add quit item
        quit = Gtk.MenuItem(label="Quit")
        quit.show()
        menu.append(quit)
        quit.connect('activate', Gtk.main_quit)

        menu.popup(None, None, None, None, event_button, event_time)

    def show_about_dialog(self, widget):
        about_dialog = Gtk.AboutDialog()
        about_dialog.set_destroy_with_parent(True)
        about_dialog.set_icon_name(icon)
        about_dialog.set_name(tip)
        about_dialog.set_copyright("2022 Peter Starfinger")
        about_dialog.set_comments((subprocess.getoutput('gettext "With the Starbuntu app \'systray-item-edit\' the command\n"') + '\n' + app + ' ' + params + subprocess.getoutput('gettext "\nhas been put into the system tray.\n"') + '\n' + subprocess.getoutput('gettext "With \'→ Permanent\' it remains there permanently\n"') + '\n' + subprocess.getoutput('gettext "what can be revoked with \'Quit permanent\'."')))
        about_dialog.set_authors(['Peter Starfinger <info@die-starfingers.de>'])
        about_dialog.run()
        about_dialog.destroy()

    def make_permanent(self, widget):
        title = subprocess.getoutput('gettext "Error"')
        msg_add = subprocess.getoutput('gettext "The command \'"') + app + ' ' + params + subprocess.getoutput('gettext "\' has permanently been added to the system tray."')
        msg_noadd = subprocess.getoutput('gettext "The command \'"') + app + ' ' + params + subprocess.getoutput('gettext "\' resides already permanently in the system tray!"')
        with open(filename, 'a+') as cmds_to_systray:
            lines = cmds_to_systray.readlines()
            to_add = 'systray-item-edit ' + app + ' "' + params + '"'
            found = False
            for line in lines:
                if to_add in line:
                    found = True
            if not found:
                cmds_to_systray.write('systray-item-edit ' + app + ' "' + params + '" ' + icon + ' "' + tip + '" &')
                window = Tk()
                window.wm_withdraw()
                window.geometry("1x1+" + str(window.winfo_screenwidth() // 2) + "+" + str(window.winfo_screenheight() // 2))
                messagebox.showinfo('Ok', msg_add)
                window.destroy()
            else:
                window = Tk()
                window.wm_withdraw()
                window.geometry("1x1+" + str(window.winfo_screenwidth() // 2) + "+" + str(window.winfo_screenheight() // 2))
                messagebox.showinfo(title, msg_noadd)
                window.destroy()

    def quit_permanent(self, widget):
        title = subprocess.getoutput('gettext "Error"')
        msg_del = subprocess.getoutput('gettext "The command \'"') + app + ' ' + params + subprocess.getoutput('gettext "\' has been removed from the permanent system tray."')
        msg_nodel = subprocess.getoutput('gettext "The command \'"') + app + ' ' + params + subprocess.getoutput('gettext "\' doesn\'t reside in the permanent system tray!"')
        with open(filename, 'r') as cmds_to_systray:
            lines = cmds_to_systray.readlines()
        to_delete = 'systray-item-edit ' + app + ' "' + params + '"'
        found = False
        for line in lines:
            if to_delete in line:
                found = True
        if found:
            with open(filename, 'w') as cmds_to_systray:
                for line in lines:
                    if to_delete not in line:
                        cmds_to_systray.write(line)
            window = Tk()
            window.wm_withdraw()
            window.geometry("1x1+" + str(window.winfo_screenwidth() // 2) + "+" + str(window.winfo_screenheight() // 2))
            messagebox.showinfo('Ok', msg_del)
            window.destroy()
        else:
            window = Tk()
            window.wm_withdraw()
            window.geometry("1x1+" + str(window.winfo_screenwidth() // 2) + "+" + str(window.winfo_screenheight() // 2))
            messagebox.showinfo(title, msg_nodel)
            window.destroy()

if __name__ == "__main__":
    # Collect parameters
    params_collector = GetParams()
    # Start the systray app with the collected parameters
    SystrayIconApp()
    Gtk.main()
