#! /usr/bin/python3
from PySide6.QtWidgets import QApplication
from PySide6.QtQuick import QQuickView
from PySide6.QtCore import QUrl, QObject, Slot, Signal,Property
import os
import subprocess
import sys
import shutil

class Tunnel(QObject):
	
	def __init__(self):

		QObject.__init__(self)
		self.clearCache()

	#def __init	

	def clearCache(self):

		clear=False
		user=os.environ["USER"]
		versionFile="/home/%s/.config/lliurex-easy-sites.conf"%user
		cachePath1="/home/%s/.cache/lliurex-easy-sites"%user
		cachePath2="/home/%s/.cache/lliurex-easy-sites-gui"%user
		installedVersion=self.getPackageVersion()

		try:
			if not os.path.exists(versionFile):
				with open(versionFile,'w') as fd:
					fd.write(installedVersion)
					fd.close()

				clear=True

			else:
				with open(versionFile,'r') as fd:
					fileVersion=fd.readline()
					fd.close()

				if fileVersion!=installedVersion:
					with open(versionFile,'w') as fd:
						fd.write(installedVersion)
						fd.close()
					clear=True
		except:
			clear=True
		
		if clear:
			if os.path.exists(cachePath1):
				shutil.rmtree(cachePath1)
			if os.path.exists(cachePath2):
				shutil.rmtree(cachePath2)

	#def clearCache

	def getPackageVersion(self):

		installedVersion="/var/lib/lliurex-easysites/version"
		pkgVersion=""

		if os.path.exists(installedVersion):
			with open(installedVersion,'r') as fd:
				pkgVersion=fd.readline()
				fd.close()

		return pkgVersion

	#def getPackageVersion

	@Slot(str)
	def on_authenticated(self,passwd):
		
		self.passwd=passwd
	
	#def on_authenticated
		
	@Slot(str)
	def onTicket(self, ticket):
		tk=ticket.replace(' ','##U+0020##')
		passwd="'"+self.passwd+"'"
		if len(sys.argv)==1:
			os.system("/usr/sbin/lliurex-easy-sites-gui %s %s &"%(tk,passwd))
		elif len(sys.argv)==2:			
			sync_folder=sys.argv[1]
			os.system("/usr/sbin/lliurex-easy-sites-gui %s %s %s &"%(tk,passwd,sync_folder))

		app.quit()
	
	#def onTicket
	

#class Tunnel

app = QApplication([])
app.setDesktopFileName("lliurex-easy-sites");
tunnel = Tunnel()
view = QQuickView()
view.rootContext().setContextProperty("tunnel", tunnel)
url = QUrl("/usr/lib/python3.12/dist-packages/easysites/rsrc/login.qml")
view.setSource(url)
view.show()
ret=app.exec()
del view
del app
sys.exit(ret)
