#! /usr/bin/python3
from PySide2.QtWidgets import QApplication
from PySide2.QtQuick import QQuickView
from PySide2.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.adiServer="/usr/bin/natfree-adi"
		self.adiClient="/usr/bin/natfree-tie"
		self.clearCache()
		self.isStandAlone()

	#def __init	

	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=False
		self._isClient=False

		if os.path.exists(self.adiServer):
			self._standAlone=True
			return

		try:
			result=subprocess.check_output(['lliurex-version', '-v'],text=True)
			flavours=[x.strip() for x in result.split(",")]
		except (subprocess.CalledProcessError,FileNotFoundError):
			self._standAlone=True
			return

		if any('server' in item for item in flavours):
			return

		self._isClient=any('client' in item for item in flavours)

		isDesktop=any('desktop' in item for item in flavours)
			
		if isDesktop:
			if os.path.exists(self.adiClient):
				self._isClient=True
			else:
				self._standAlone=True


		if self._isClient and isDesktop:
			if self._checkConnectionWithServer():
				self._standAlone=False
			else:
				self._isClient=False
				self._standAlone=True

	#def is_StandAlone
	
	def _checkConnectionWithServer(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 _checkConnectionWithServer
	
	def _getStandAlone(self):

		return self._standAlone

	#def _getStandAlone

	def _getIsClient(self):
		
		return self._isClient

	#def _getIsClient	

	standAlone=Property(bool,_getStandAlone,constant=True)
	isClient=Property(bool,_getIsClient,constant=True)

	@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([])
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)
