#!/usr/bin/python3

import sys
import gi
import subprocess
import threading
import time
import os
import pwd
import re

import logging

gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, Gdk, Gio, GLib, Graphene
from PIL import Image
import random
import string
import locale
import gettext

SUPPORT_URL = "https://uncom.tech/support_channels/"

gettext.bindtextdomain("update-manager", "/usr/share/locale")
gettext.textdomain("update-manager")
translation = gettext.translation("update-manager", fallback=True)
if sys.version >= '3':
    _ = translation.gettext
else:
    _ = translation.ugettext

try:
    locale.setlocale(locale.LC_ALL, "")
except:
    pass


class MainWindow(Gtk.ApplicationWindow):

    workDone = False

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)



        # window
        self.set_default_size(400, 200)
        self.set_title(_("System Update"))
        self.set_resizable(False)

        self.main_box = Gtk.Box(spacing=0, orientation=Gtk.Orientation.VERTICAL)
        self.set_child(self.main_box)

        # box1
        self.box1 = Gtk.Box(spacing=5, orientation=Gtk.Orientation.VERTICAL)
        self.box1.set_margin_start(20)
        self.box1.set_margin_end(20)
        self.box1.set_margin_top(20)
        self.box1.set_margin_bottom(20)
        self.main_box.append(self.box1)  

        # box1 label1
        self.label1 = Gtk.Label()
        self.label1.set_markup(_("<big>Update is in progress</big>"))
        self.label1.set_wrap(True)
        self.label1.set_justify(Gtk.Justification.CENTER)
        self.label1.set_xalign(0.5)
        self.box1.append(self.label1)

        # box3
        self.box3 = Gtk.Box(spacing=10, orientation=Gtk.Orientation.VERTICAL)
        self.box1.set_margin_start(20)
        self.box1.set_margin_end(20)
        self.box1.set_margin_top(20)
        self.box1.set_margin_bottom(20)
        self.main_box.append(self.box3)

        # box3 spinner
        self.spinner = Gtk.Spinner()
        self.box3.append(self.spinner)
        self.spinner.set_visible(True)
        self.spinner.set_vexpand(True)
        self.spinner.start()

        # box3 label_A
        self.label_A = Gtk.Label(label=_("Please wait"))
        self.label_A.set_valign(Gtk.Align.END)
        self.label_A.set_wrap(True)
        self.label_A.set_margin_bottom(20)
        self.box3.append(self.label_A)

        # box3 box_buttons
        self.box_buttons = Gtk.Box(spacing=5, orientation=Gtk.Orientation.HORIZONTAL)
        self.box_buttons.set_margin_top(20)
        self.box3.append(self.box_buttons)
        self.box3.set_margin_bottom(20)
        self.button_close = Gtk.Button(label=_("Close"))
        self.button_close.set_hexpand(True)
        self.button_close.set_halign(Gtk.Align.END)
        self.button_close.set_margin_end(20)
        self.button_close.connect("clicked", self.on_button_close_clicked)
        self.box_buttons.append(self.button_close)
        self.box_buttons.set_visible(False)

        # end of UI formation
        thread = threading.Thread(target=self.run_command)
        thread.start()

    def on_button_close_clicked(self, button):
        print("Close clicked")
        exit(0)

    def on_work_done(self):
        print("on_work_done: work is done!")
        with open('/var/log/uncom-partial-update.log') as f:
            for line in f:
                pass
            last_line = line
        logging.debug("on_work_done: last_line = %s", last_line)
        if "Final_success" in last_line:
            self.label_A.set_label(_("Update completed successfully, please reboot"))
        else:
            self.label_A.set_label(_("Update completed with errors, log file: /var/log/uncom-partial-update.log"))


    def run_command(self):
        # Disable sleep mode
        # subprocess.call(["echo lock_me > /sys/power/wake_lock"])
        # Run the command asynchronously
        print("Starting update")
        subprocess.run(["/usr/bin/pkexec", "/usr/bin/do-uncom-partial-update"] + sys.argv[1:])
        self.workDone = True
        # After the command finishes, hide the progress bar and re-enable the button
        # GLib.idle_add(lambda: self.spinner.set_visible(False))
        GLib.idle_add(lambda: self.spinner.stop())
#        self.spinner.set_visible(True)
        GLib.idle_add(lambda: self.spinner.set_visible(False))
        GLib.idle_add(lambda: self.box_buttons.set_visible(True))
        GLib.idle_add(lambda: self.button_close.set_visible(True))
        GLib.idle_add(lambda: self.label_A.set_visible(True))
        GLib.idle_add(lambda: self.on_work_done())

        if self.workDone:
#            print("XXX: self.workDone = True")
#            thread = threading.Thread(target=self.run_reboot)
#            thread.start()
            exit(0)
        else:
            print("XXX: self.workDone = False")
#            thread = threading.Thread(target=self.run_command)
#            thread.start()



class MyApp(Gtk.Application):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.connect('activate', self.on_activate)

    def on_activate(self, app):
        self.win = MainWindow(application=app)
        self.win.present()

print("Running application as: " + os.getlogin())

main_app = MyApp(application_id="tech.uncom.kernel68-update")
main_app.run()
