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

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

		QObject.__init__(self)
		self.clearCache()

	#def __init	

	def clearCache(self):

		clear=False
		user=os.environ["USER"]
		versionFile="/home/%s/.config/lliurex-easy-sites.conf"%user
		cachePath="/home/%s/.cache/lliurex-easy-sites"%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(cachePath):
				shutil.rmtree(cachePath)

	#def clearCache

	def getPackageVersion(self):

		command = "LANG=C LANGUAGE=en apt-cache policy lliurex-easy-sites"
		p = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE)
		installed = None
		for line in iter(p.stdout.readline,b""):
			if type(line) is bytes:
				line=line.decode()

			stripedline = line.strip()
			if stripedline.startswith("Installed"):
				installed = stripedline.replace("Installed: ","")

		return installed

	#def getPackageVersion

	@Slot(str)
	def on_authenticated(self,passwd):
		
		self.passwd=passwd
	
	#def on_authenticated
		
	@Slot(str)
	def on_ticket(self, ticket):
	
		if len(sys.argv)>1:
			sync_folder=sys.argv[1]
		else:
			sync_folder=None

		tk=ticket.replace(' ','##U+0020##')
		passwd="'"+self.passwd+"'"
		os.system("/usr/sbin/lliurex-easy-sites-gui %s %s %s &"%(sync_folder,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/easysites/rsrc/login.qml")
view.setSource(url)
view.show()
ret=app.exec_()
del view
del app
sys.exit(ret)