#! /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	

	def clearCache(self):

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

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

	#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()
				fd.close()

		return pkgVersion

	#def getPackageVersion

	def isStandAlone(self):

		versionReference=["adi","desktop"]
		self._standAlone=True
		self._isClient=False
		isDesktop=False

		if not os.path.exists(self.adiServer):
			if os.path.exists(self.adiClient):
				if self._checkConnectionWithADI():
					self._isClient=True
					self._standAlone=False
		'''
		flavours=[]
		cmd='lliurex-version -v'
		p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
		result=p.communicate()[0]

		if type(result) is bytes:
			result=result.decode()

		for x in result.split(","):
			if x.strip() in versionReference:
				flavours.append(x.strip())

		for item in flavours:
			if 'adi' in item:
				break
			elif 'desktop' in item:
				isDesktop=True
				self._standAlone=True
				
		if isDesktop:
			if os.path.exists(self.adiClient):
				if self._checkConnectionWithADI():
					self._isClient=True
					self._standAlone=False
		'''
	#def is_StandAlone
	
	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
	
	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=None
		if self._isClient:
			passwd="'"+self.passwd+"'"
		os.system("python3 /usr/share/lliurex-shutdowner/lliurex-shutdowner-gui.py %s %s &"%(ticket,passwd))
		app.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)
