#! /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
		self.home=os.path.expanduser("~")
		versionFile=os.path.join(self.home,".config/easy-login-gui.conf")
		cachePath=os.path.join(self.home,".cache/easy-login-gui")
		installedVersion=self._getPackageVersion()

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

			clear=True

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

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

	#def clearCache

	def _getPackageVersion(self):

		packageVersionFile="/var/lib/easy-login-gui/version"
		pkgVersion=""
		
		if os.path.exists(packageVersionFile):
			with open(packageVersionFile,'r') as fd:
				pkgVersion=fd.readline().strip()

		return pkgVersion

	
	#def getPackageVersion

	@Slot(str)
	def onTicket(self, ticket):
		
		ticket_escaped=ticket.replace(' ','##U+0020##')
		cmd = ["/usr/share/easy-login/gui/easy-login-ui", ticket_escaped]
		subprocess.Popen(cmd)
		QApplication.quit()

	#def onTicket
	

#class Tunnel

app = QApplication(sys.argv)
app.setDesktopFileName("easy-login-gui")
tunnel = Tunnel()
view = QQuickView()
view.rootContext().setContextProperty("tunnel", tunnel)
url = QUrl.fromLocalFile("/usr/share/easy-login/gui/rsrc/login.qml")
view.setSource(url)

if view.status() == QQuickView.Error:
	sys.exit(-1)

view.show()
ret=app.exec()
del view
del app
sys.exit(ret)
