#!/usr/bin/python3

import sys
import argparse
import gi
import stat
import subprocess
import os
import string
import random
import re
import shutil
import configparser
import gettext
import threading
import time
from PIL import Image

gi.require_version("Gtk", "4.0")
gi.require_version('Adw', '1')
from gi.repository import GLib, Gtk, Adw, Gdk

# This block is about localization (this is global path, will not work during local testing)
text_domain = "uncom-hotfix-logtune"
gettext.bindtextdomain(text_domain, '/usr/share/uncom/uncom-hotfix-logtune/locale')
gettext.textdomain(text_domain)
_ = gettext.gettext

# Define global links to resources here (this is global path, will not work during local testing)
CUSTOM_IMAGE = "/usr/share/icons/Yaru/48x48@2x/status/dialog-warning.png"
DONT_SHOW_CONF = "~/.config/uncom/dont_show_check_warning"
PROBLEM_UNKNOWN = "unknown"

class WindowMain(Gtk.ApplicationWindow):
    def __init__(self, **kargs):
        super().__init__(**kargs, title=_("Warning!"))
        self.set_resizable(False)
        self.set_default_size(400, 200)

        if args.problem:
            self.problem = args.problem
        else:
            self.problem = PROBLEM_UNKNOWN

        # biggest log, only for problem == "size_varlog"
        if args.log:
            self.log = args.log
        else:
            self.log = PROBLEM_UNKNOWN


        print("init: self.problem =", self.problem)

        # Common top level container
        main = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        main.props.margin_start = 25
        main.props.margin_end = 25
        main.props.margin_top = 25
        main.props.margin_bottom = 25
        self.set_child(main)

        # Visual container
        self.visual_container = Gtk.Grid(orientation=Gtk.Orientation.HORIZONTAL, column_spacing=10, column_homogeneous=True)
#        self.visual_container = Gtk.Grid(orientation=Gtk.Orientation.HORIZONTAL, column_spacing=10)
        main.append(self.visual_container)

        # Buttons containere
        horiontal_buttons = Gtk.Grid(column_homogeneous=True, row_homogeneous=True, column_spacing=10)
        horiontal_buttons.props.margin_top = 25
        main.append(horiontal_buttons)

        # Image (put it in Visual container)
        self.picture = Gtk.Picture.new_for_filename(CUSTOM_IMAGE)
#        self.picture.props.vexpand = True
#        self.picture.props.hexpand = True
#        self.picture.set_margin_end(10)
        self.visual_container.attach(self.picture, 0, 0, 1, 1)

        # Vertical message container
        vertical_message = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        vertical_message.props.margin_top = 20
        self.visual_container.attach(vertical_message, 1, 0, 3, 1)

        # Messages (put it in Message container)
        label_message = Gtk.Label()
        if self.problem == "size_varlog":
            label_message.set_markup(_("System logs size is too big: more then 3 Gb."))
        else:
            label_message.set_markup(_("System logs are growing unexpectedly."))
        label_message.set_halign(Gtk.Align.START)
        label_message.props.hexpand = True
        vertical_message.append(label_message)

        # Message 2
        label_message2 = Gtk.Label()
        if self.problem == "size_varlog":
            label_message2.set_markup(_("You can clean logs in /var/log/ or contact the support: http://uncom.tech/support_channels"))
        else:
            label_message2.set_markup(_("Please contact the support: http://uncom.tech/support_channels"))
        label_message2.set_halign(Gtk.Align.START)
        label_message2.props.hexpand = True
        vertical_message.append(label_message2)

        # Show possible problem if we know it
        if "unknown" not in self.problem:
            label_problem = Gtk.Label()
            if self.problem == "size_varlog":
                label_problem.set_markup(_("<b>Possible problem log: </b>") + self.log)
            elif self.problem == "nouveau":
                label_problem.set_markup(_("<b>Possible reason: </b>") + _("Nouveau video driver error"))
            elif self.problem == "aer":
                label_problem.set_markup(_("<b>Possible reason: </b>") + _("PCI AER: pci device driver problem"))
            elif self.problem == "vkteams":
                label_problem.set_markup(_("<b>Possible reason: </b>") + _("VK Teams debug logs"))
            elif self.problem == "ybrowser":
                label_problem.set_markup(_("<b>Possible reason: </b>") + _("Yandex Browser debug logs"))
            else:
                label_problem.set_markup(_("<b>Possible reason: </b>") + (self.problem))
            label_problem.set_halign(Gtk.Align.START)
            label_problem.props.hexpand = True
            label_problem.props.margin_top = 10
            vertical_message.append(label_problem)

        # Dont show checkbox if problem unknown
        if "unknown" not in self.problem:
            check_btn = Gtk.CheckButton.new_with_label(_("Don't show it again"))
            check_btn.connect("toggled", self.on_dont_show_toggled)
            check_btn.props.margin_top = 25
            check_btn.set_halign(Gtk.Align.START)
            vertical_message.append(check_btn)

        # Left button (put it in Buttons container)
        self.button_l = Gtk.Button.new_with_label(_("Close"))
        self.button_l.connect('clicked', self.on_click_close)
        horiontal_buttons.attach(self.button_l, 0, 0, 1, 1)

        # Right button (put it in Buttons container)
        self.button_r = Gtk.Button.new_with_label(_("Contact Telegram"))
        self.button_r.connect('clicked', self.on_click_write)
        self.button_r.add_css_class('suggested-action')
        horiontal_buttons.attach(self.button_r, 1, 0, 1, 1)

        self.dontshow = False

    def on_dont_show_toggled(self, _button):
        print ("on_dont_show_toggled: active =", _button.get_active())
        self.dontshow = _button.get_active()

    def write_settings(self):
        file_path = os.path.expanduser(DONT_SHOW_CONF)  # Expands to /home/username/conf.txt
        print("tuning ", DONT_SHOW_CONF)
        with open(file_path, 'r') as file:
            if self.problem + "_disabled=true" in file.read():
                print("String found!")
            else:
                print("String not found, adding")
                os.system("echo " + self.problem + "_disabled=true >> " + DONT_SHOW_CONF)

    def on_click_close(self, _button):
        if self.dontshow:
            self.write_settings()
        sys.exit(0)

    def on_click_write(self, _button):
        if self.dontshow:
            self.write_settings()
        os.system("xdg-open http://uncom.tech/support_channels")
#        subprocess.Popen(["xdg-open", "http://uncom.tech/support_channels"])
        sys.exit(0)

def on_key_press(keyval, keycode, state, user_data, win):
    if keycode == Gdk.KEY_Escape:
        sys.exit(0)

class Application(Adw.Application):
    def __init__(self):
        super().__init__(application_id="tech.uncom.uncom-app-show-message")
        GLib.set_application_name(_("Uncom Show Message"))

    def do_activate(self):
        window = WindowMain(application=self)

        # Connect key events
        keycont = Gtk.EventControllerKey()
        keycont.connect('key-pressed', on_key_press, window)
        window.add_controller(keycont)

        window.present()

#parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(
    description="Uncom App message application. Can be used in GUI.",
    epilog="Start without parameters is not supported")

parser.add_argument('-g', '--gui', action='store_true', help='run with graphical UI, used for desktop sessions')
parser.add_argument('-p', '--problem', type=str, help='problem specified')
parser.add_argument('-l', '--log', type=str, help='log name')

args = parser.parse_args()

if args.gui: # run in GUI mode
    # clear arguments so GTK will not trigger on them
    sys.argv = [sys.argv[0]]


    app = Application()
    exit_status = app.run(sys.argv)
    sys.exit(exit_status)
else: # run in command line mode
    print ("This app should not be run from console")
