# Reborn Maintenance App Trigger Handlers
# Created by Azaiel for RebornOS
# 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: Azaiel

# This ensures that the Gtk version is 3.0
import subprocess
import gi
import os
import time
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("Mycroft on RebornOS")
try:
    import httplib
except:
    import http.client as httplib

# 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. Depending on your setup, Mycroft may not work properly").show()

workingDirectory = os.path.dirname(os.path.realpath(__file__))
bashFile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Bash', 'Maintenance.sh'))
settingsFile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Settings', 'settings.json'))

# Create Handlers (Triggers) for each item
class Handler:
    with open(settingsFile) as outfile:
        self.settings = json.load(outfile)

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

################################################################################
############################### Buttons ########################################
################################################################################

# Start Mycroft Service
    def onStart(self, button):
        os.system("pkexec " + bashFile + " StartMycroft")

# Stop Mycroft Service
    def onStop(self, button):
        os.system("pkexec " + bashFile + " StopMycroft")

# Build / Update Mycroft
    def onBuild(self, button):
        os.system("pkexec " + bashFile + " BuildMycroft " + self.settings["terminal"])

# Type queries for Mycroft
    def onEnter(self, pkgtxt):
        enteredText = pkgtxt.get_text()
        Notify.Notification.new(enteredText).show()
        os.system("pkexec " + bashFile + " TextMycroft " + enteredText)

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

builder = Gtk.Builder()
builder.add_from_file(workingDirectory + "/mycroft-reborn.glade")
builder.connect_signals(Handler())

window1 = builder.get_object("mycroftWindow")
window1.show_all()

Gtk.main()

Notify.uninit()
