#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 12:04:53 2024

@author: angoosh
"""
import sys
import os
import gi
import subprocess
import json
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, Gdk, Gio

APPID = "com.angoosh.RDPConnect"
HOMEDIR = os.path.expanduser('~')

print(HOMEDIR)

conn_info = {}
settings = {}

def load_config():
    global conn_info, settings
    loaded_json = ""
    try:
        with open(HOMEDIR+"/.config/rdpconnect/connection.json", "r") as connection_file:
            for line in connection_file:
                loaded_json += line
            
            conn_info = json.loads(loaded_json)
    except:
        print("[WARN] FILE: "+HOMEDIR+"/.config/rdpconnect/connection.json doesn't exist")
    
    loaded_json = ""
    try:
        with open(HOMEDIR+"/.config/rdpconnect/settings.json", "r") as settings_file:
            for line in settings_file:
                loaded_json += line
            
            settings = json.loads(loaded_json)
    except:
        print("[WARN] FILE: "+HOMEDIR+"/.config/rdpconnect/settings.json doesn't exist")
        

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

    def on_activate(self, app):
        builder = Gtk.Builder()
        builder.add_from_file(APPID+".ui")
        
        css_provider = Gtk.CssProvider()
        css_provider.load_from_file(Gio.File.new_for_path("style.css"))
        Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        
        connect = builder.get_object("connect")
        connect.connect("clicked", self.connectRDP)
        
        self.ip = builder.get_object("ip")
        self.user = builder.get_object("user")
        self.passwd = builder.get_object("pass")
        
        self.save_conf = builder.get_object("save_conf")
        
        try:
            if settings["save_conn"]:
                self.ip.get_buffer().set_text(str(conn_info["ip"]), len(conn_info["ip"]))
                self.user.get_buffer().set_text(str(conn_info["user"]), len(conn_info["user"]))
                self.passwd.get_buffer().set_text(str(conn_info["passwd"]), len(conn_info["passwd"]))
                
                self.save_conf.set_active(True)
        except:
            pass
        
        self.win = builder.get_object("main_window")
        self.win.set_application(self)
        self.win.present()
        
    def saveConnConf(self):
        if settings["save_conn"]:
            print("Saving connection config to "+HOMEDIR+"/.config/rdpconnect/connection.json")
            with open(HOMEDIR+"/.config/rdpconnect/connection.json", "w") as connection_file:
                js = json.dumps(conn_info, sort_keys=True, indent=4, separators=(',', ': '))
                connection_file.write(js)
        else:
            with open(HOMEDIR+"/.config/rdpconnect/connection.json", "w") as connection_file:
                connection_file.write("")
        
        print("Saving settings config to "+HOMEDIR+"/.config/rdpconnect/settings.json")
        with open(HOMEDIR+"/.config/rdpconnect/settings.json", "w") as settings_file:
            js = json.dumps(settings, sort_keys=True, indent=4, separators=(',', ': '))
            settings_file.write(js)
        
    def connectRDP(self, button):
        conn_info["ip"] = self.ip.get_buffer().get_text()
        conn_info["user"] = self.user.get_buffer().get_text()
        conn_info["passwd"] = self.passwd.get_buffer().get_text()
        
        if self.save_conf.get_active():
            settings["save_conn"] = True
        else:
            settings["save_conn"] = False
        if not "extra_params" in settings:
            settings["extra_params"] = []
        
        self.saveConnConf()
        subprocess.Popen(["flatpak", "run", "com.freerdp.FreeRDP", "/v:"+str(conn_info["ip"]), "/u:"+str(conn_info["user"]), "/p:"+str(conn_info["passwd"])]+settings["extra_params"])
        #subprocess.run(["xfreerdp", "/v:"+str(ip), "/u:"+str(user), "/p:"+str(passwd)])
        
if not os.path.isdir(HOMEDIR+"/.config/rdpconnect"):
    os.makedirs(HOMEDIR+"/.config/rdpconnect")
#subprocess.run(["ls", "-a", HOMEDIR])

load_config()
app = MyApp(application_id=APPID)
app.run(sys.argv)
