# 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 json
import os
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk, GdkPixbuf
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("Unnecessary Packages")
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__ ), '..'))
gladeFile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'Glade', 'RebornUnnecessary.glade'))
localeDirectory = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'TranslationFiles'))

# 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. The following operations will not work").show()

# Create Handlers (Triggers) for each item
class Handler:

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

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

# Remove Packages
    def clickRemovePackages(self, button):
        if os.path.getsize(workingDirectory + '/package-files.txt') > 0:
            os.system('pkexec pacman -Rns - < ' + workingDirectory + '/package-files.txt --noconfirm')

            Notify.Notification.new("Unnecessary Packages Removed").show()
            # Refresh Package List
            os.system('rm -f ' + workingDirectory + '/package-files.txt')
            os.system('pacman -Qdtq >' + workingDirectory + '/package-files.txt')
            with open(workingDirectory + '/package-files.txt', 'r') as pacFile:
                data = pacFile.read()
                builder.get_object("fileContentsView").get_buffer().set_text(data)
        else:
            Notify.Notification.new("No Packages To Remove").show()

# Edit Package List
    def updateText(self, button):
        # Refresh Package List
        with open(workingDirectory + '/package-files.txt', "w") as file_handle:
            # Get the buffer object from fileContentsView
            buffer = builder.get_object("fileContentsView").get_buffer()
            # Write the contents of the buffer to a file
            file_handle.write(buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), include_hidden_chars=False))

        # Let user know change was saved
        Notify.Notification.new("Changes Saved").show()

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

builder = Gtk.Builder()
builder.add_from_file(gladeFile)
builder.connect_signals(Handler())

# =====================================
# View the file when the window pops up
# =====================================
with open(workingDirectory + '/package-files.txt', 'r') as pacFile:
    data = pacFile.read()
    builder.get_object("fileContentsView").get_buffer().set_text(data)
# =====================================

# Set Button Labels
with open(localeDirectory + '/translations_' + os.getenv('LANG').split('_')[0] + '.json') as json_file:
    locale = json.load(json_file)
    builder.get_object("RemovePackagesButton").set_label(locale["RebornOSFIRE"]["SystemTasksTab"]["SystemMaintenanceTab"]["RemoveUnnecessaryProgramsDialog"]["RemovePackagesButton"])
    builder.get_object("EditListButton").set_label(locale["RebornOSFIRE"]["SystemTasksTab"]["SystemMaintenanceTab"]["RemoveUnnecessaryProgramsDialog"]["EditListButton"])

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

Gtk.main()

Notify.uninit()
