# RUM Settings App Trigger Handlers
# Created by Keegan for RebornOS and Arch Linux
# This is an open-source project using Python3.  Feel free to use
# what you'd like, but please give credit!  Improvements are always welcome!
# RebornOS Discord: Keegan

# Import necessary modules
import subprocess
import gi
import os
import json
import fileinput
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("RebornOS FIRE")
try:
    import httplib
except:
    import http.client as httplib

# Create variables for both the current working directory and the location of the settings file
workingDirectory = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
localeDirectory = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'TranslationFiles'))
settingsFile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Settings', 'settings.json'))
packageFile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Settings', 'packages.txt'))
bashFile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Bash', 'StartupChecks.sh'))

# Check for Internet connection
conn = httplib.HTTPConnection("www.google.com", timeout=5)
try:
    conn.request("HEAD", "/")
    conn.close()
except:
    conn.close()
    Notify.Notification.new("Lacking Internet connection. Some options may not work").show()

# Create Handlers (Triggers) for each item
class Handler:
    def __init__(self):
        # Create settings file if it does not already exist, as well as declare the self.settings array
        if not os.path.isfile(settingsFile):
            with open(settingsFile, 'w+') as outfile:
                self.settings = {
                    "terminal": "",
                    "chosen_date": {
                        "day": 0,
                        "month": 0,
                        "year": 0
                    }
                }
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))
        else:
            with open(settingsFile) as outfile:
                self.settings = json.load(outfile)

# Close the window
    def onDestroy(self, *args):
        Gtk.main_quit()

################################################################################
############################### ComboBox Terminal Settings ############################
################################################################################

    def setTerminal(self, combo):
        tree_iter = combo.get_active_iter()
        if tree_iter is not None:
            model = combo.get_model()
            chosenTerminal = model[tree_iter][0]
            if chosenTerminal == "Deepin Terminal":
                print("Deepin Terminal successfully selected!")
                self.settings["terminal"]= "deepin-terminal --execute "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "GNOME Terminal":
                print("GNOME Terminal successfully selected!")
                self.settings["terminal"] = "gnome-terminal -- "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "Konsole":
                print("Konsole Terminal successfully selected!")
                self.settings["terminal"] = "konsole -e "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "Xterm":
                print("Xterm Terminal successfully selected!")
                self.settings["terminal"] = "xterm -e "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "Terminology":
                print("Terminology successfully selected!")
                self.settings["terminal"] = "terminology -e "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "LXTerminal":
                print("LXTerminal successfully selected!")
                self.settings["terminal"] = "lxterminal -e "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "MATE Terminal":
                print("MATE Terminal successfully selected!")
                self.settings["terminal"] = "mate-terminal -e "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            elif chosenTerminal == "XFCE4 Terminal":
                print("XFCE4 Terminal successfully selected!")
                self.settings["terminal"] = "xfce4-terminal -e "
                with open(settingsFile, 'w+') as outfile:
                    outfile.write(json.dumps(self.settings, indent = 4))

            else:
                Notify.Notification.new("ERROR! Abort! Abort!!!").show()

################################################################################
############################### Drawing App Window #################################
################################################################################

builder = Gtk.Builder()
builder.add_from_file(workingDirectory + "/Glade/RebornSettings.glade")
builder.connect_signals(Handler())

# =====================================
# Set text through the use of keys from the JSON files used for translations
# =====================================
with open(localeDirectory + '/translations_' + os.getenv('LANG').split('_')[0] + '.json') as json_file:
    locale = json.load(json_file)

    builder.get_object("TerminalSelectionDialog").set_text(locale["RebornOSFIRE"]["Settings"]["TerminalSelectionDialog"])
    builder.get_object("ExitSettings").set_label(locale["RebornOSFIRE"]["Settings"]["ExitSettings"])

    # Checks for Deepin Terminal
    isTerminalInstalled = int(subprocess.check_output("which 'deepin-terminal' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["DeepinTerminal"])
    # Checks for GNOME Terminal
    isTerminalInstalled = int(subprocess.check_output("which 'gnome-terminal' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["GnomeTerminal"])
    # Checks for Konsole
    isTerminalInstalled = int(subprocess.check_output("which 'konsole' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["Konsole"])
    #Checks for Mate Terminal
    isTerminalInstalled = int(subprocess.check_output("which 'mate-terminal' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["MateTerminal"])
    # Checks for XFCE Terminal
    isTerminalInstalled = int(subprocess.check_output("which 'xfce4-terminal' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["Xfce4Terminal"])
    # Checks for LXTerminal
    isTerminalInstalled = int(subprocess.check_output("which 'lxterminal' 2> /dev/null | wc -l ", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["LXTerminal"])
    # Checks for Xterm
    isTerminalInstalled = int(subprocess.check_output("which 'xterm' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["Xterm"])
    # Checks for Terminology
    isTerminalInstalled = int(subprocess.check_output("which 'terminology' 2> /dev/null | wc -l", shell=True).decode())
    if isTerminalInstalled > 0:
        builder.get_object("TerminalSelectionBox").append_text(locale["RebornOSFIRE"]["Settings"]["Terminology"])

window = builder.get_object("RebornSettings")
window.show_all()

Gtk.main()

Notify.uninit()
