#! /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 subprocess
import sys
import shutil

import gettext
gettext.textdomain("lliurex-guard")
_=gettext.gettext

class Tunnel(QObject):
	
	def __init__(self):

		QObject.__init__(self)
		self.clearCache()
		self.canRun()
		self.isStandAlone()

	#def __init	

	def clearCache(self):

		clear=False
		user=os.environ["USER"]
		configPath="/home/%s/.config/"%user
		versionFile=os.path.join(configPath,"lliurex-guard.conf")
		cachePath="/home/%s/.cache/lliurex-guard"%user
		installedVersion=self.getPackageVersion()

		if not os.path.exists(configPath):
			os.mkdir(configPath)
			
		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(cachePath):
				shutil.rmtree(cachePath)

	#def clearCache

	def getPackageVersion(self):

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

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

		return pkgVersion

	#def getPackageVersion

	def canRun(self):

		normalizedFlavours=["adi","pro","alu"]
		flavoursInstalled=[]
		
		cmd=["lliurex-version", "-v"]
		try:
			result=subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors='ignore')
			pout = result.stdout

		except Exception:
			pout=""

		if pout:
			flavoursInstalled = [x.strip() for x in pout.split(',') if x.strip() and x.strip()!="edu"]
			runApp=all(p not in i for i in flavoursInstalled for p in normalizedFlavours)

		if not runApp:
			msg=_("This version of LliureX-Guard can only be used on computers configured as desktop")
			cmd = [
            	"kdialog",
            	"--title", "LliureX-Guard",
            	"--icon", "lliurex-guard",
            	"--sorry", msg
        	]
			try:
				subprocess.run(cmd,check=True)
			except Exception:
				pass

			sys.exit(1)
	
	#def canRun	

	def isStandAlone(self):

		self._standAlone=False
		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()
		flavours = [ x.strip() for x in result.split(',') ]

		for item in flavours:
			if 'server' in item:
				self._standAlone=False
				break
			elif 'client' in item:
				self._standAlone=False
				break
			elif 'desktop' in item:
				self._standAlone=True

	#def is_StandAlone

	def _getStandAlone(self):

		return self._standAlone

	#def _getStandAlone	

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

	@Slot(str)
	def on_authenticated(self,passwd):
		
		self.passwd=passwd
	
	#def on_authenticated
		
	@Slot(str)
	def on_ticket(self, ticket):
	
		tk=ticket.replace(' ','##U+0020##')
		passwd="'"+self.passwd+"'"
		os.system("/usr/sbin/lliurex-guard-gui %s %s &"%(tk,passwd))
		app.quit()
	
	#def on_ticket
	

#class Tunnel

app = QApplication([])
tunnel = Tunnel()
view = QQuickView()
view.rootContext().setContextProperty("tunnel", tunnel)
url = QUrl("/usr/lib/python3/dist-packages/lliurexguard/rsrc/login.qml")
view.setSource(url)
view.show()
ret=app.exec_()
del view
del app
sys.exit(ret)
