#! /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"]
		bellVersionFile="/home/%s/.config/bell-scheduler.conf"%user
		holidayVersionFile="/home/%s/.config/python3-holidaymanager.conf"%user
		cachePath1="/home/%s/.cache/bell-scheduler"%user
		cachePath2="/home/%s/.cache/bell-scheduler-gui.py"%user
		bellInstalledVersion=self.getPackageVersion("bell")
		holidayInstalledVersion=self.getPackageVersion("holiday")


		if bellInstalledVersion!="" and holidayInstalledVersion!="":

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

				clear=True
				
			if not os.path.exists(holidayVersionFile):
				with open(holidayVersionFile,'w') as fd:
					fd.write(holidayInstalledVersion)

				clear=True

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

				if fileVersion!=bellInstalledVersion:
					with open(bellVersionFile,'w') as fd:
						fd.write(bellInstalledVersion)
						fd.close()
					clear=True
				else:
					with open(holidayVersionFile,'r') as fd:
						fileVersion=fd.readline()
						fd.close()

					if fileVersion!=holidayInstalledVersion:
						with open(holidayVersionFile,'w') as fd:
							fd.write(holidayInstalledVersion)
							fd.close()
						clear=True

		else:
			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,appName):

		if appName=="bell":
			packageVersionFile="/var/lib/bell-scheduler/version"
		elif appName=="holiday":
			packageVersionFile="/var/lib/python3-holidaymanager/version"

		pkgVersion=""

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

		return pkgVersion

	#def getPackageVersion

	@Slot(str)
	def onTicket(self, ticket):
		
		ticket=ticket.replace(' ','##U+0020##')
		if len(sys.argv)==1:
			os.system("/usr/sbin/bell-scheduler-gui %s &"%ticket)
		elif len(sys.argv)==2:
			tmpFile='"%s"'%sys.argv[1]
			os.system("/usr/sbin/bell-scheduler-gui %s %s &"%(ticket,tmpFile))
		app.quit()

	#def onTicket

#class Tunnel

app = QApplication([])
app.setDesktopFileName("bell-scheduler")
tunnel = Tunnel()
view = QQuickView()
view.rootContext().setContextProperty("tunnel", tunnel)
url = QUrl("/usr/lib/python3/dist-packages/bellscheduler/rsrc/login.qml")
view.setSource(url)
view.show()

sys.exit(app.exec())
