#! /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 sys
import subprocess
import shutil
import xmlrpc.client as n4dclient
import ssl

class Tunnel(QObject):

	def __init__(self):

		QObject.__init__(self)
		self.adiClient="/usr/bin/natfree-tie"
		self.adiServer="/usr/bin/natfree-adi"
		self.clearCache()
		self.isStandAlone()

	#def __init

	@Property(bool,constant=True)
	def standAlone(self):

		return self._standAlone

	#def standAlone

	@Property(bool,constant=True)
	def isClient(self):
		
		return self._isClient

	#def isClient

	def clearCache(self):

		clear=False
		userHome=os.path.expanduser("~")
		versionFile=os.path.join(userHome,".config/lliurex-shutdowner.conf")
		cachePath1=os.path.join(userHome,".cache/lliurex-shutdowner")
		cachePath2=os.path.join(userHome,".cache/lliurex-shutdowner-gui.py")
		cachePath3=os.path.join(userHome,".cache/shutdown-lliurex-dialog.py")

		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(cachePath1):
				shutil.rmtree(cachePath1)
			if os.path.exists(cachePath2):
				shutil.rmtree(cachePath2)
			if os.path.exists(cachePath3):
				shutil.rmtree(cachePath3)

	#def clearCache

	def getPackageVersion(self):

		packageVersionFile="/var/lib/lliurex-shutdowner/version"
		pkgVersion=""

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

		return pkgVersion

	#def getPackageVersion

	def isStandAlone(self):

		self._standAlone=True
		self._isClient=False
		isDesktop=False

		if not os.path.exists(self.adiServer) and os.path.exists(self.adiClient):
			if self._checkConnectionWithADI():
				self._isClient=True
				self._standAlone=False
		
	#def isStandAlone
	
	def _checkConnectionWithADI(self):

		try:
			context=ssl._create_unverified_context()
			client=n4dclient.ServerProxy('https://server:9779',context=context,allow_none=True)
			test=client.is_cron_enabled('','ShutdownerManager')
			return True
		except Exception as e:
			return False

	#def _checkConnectionWithADI
	
	@Slot(str)
	def on_authenticated(self,passwd):
		
		self.passwd=passwd
	
	#def on_authenticated

	@Slot(str)
	def on_ticket(self,ticket):

		ticket=ticket.replace(' ','##U+0020##')
		passwd=f"'{self.passwd}'" if self._isClient else "None"
		cmd=["python3","/usr/share/lliurex-shutdowner/lliurex-shutdowner-gui.py",ticket,passwd]
		subprocess.Popen(cmd)
		QApplication.quit()

	#def on_ticket
	
#class Tunnel	

app = QApplication([])
app.setDesktopFileName("lliurex-shutdowner")
tunnel = Tunnel()
view = QQuickView()
view.rootContext().setContextProperty("tunnel", tunnel)
url = QUrl("/usr/share/lliurex-shutdowner/rsrc/login.qml")
view.setSource(url)
view.show()
ret=app.exec()
del view
del app
sys.exit(ret)
