from __future__ import print_function
from __future__ import absolute_import
from Components.config import config
from Plugins.SystemPlugins.SoftwareManager.plugin import UpdatePlugin
from Tools import Notifications
from Screens.MessageBox import MessageBox
from enigma import eConsoleAppContainer
from .merlintimer import merlintimer
import re
from time import time
from . import _
updateSummary = re.compile('([0-9]+) upgraded, ([0-9]+) newly installed, ([0-9]+) to remove and ([0-9]+) not upgraded\.')

class MerlinUpdater:
	def __init__(self):
		pass
		
	def setTimer(self):
		print("[MerlinUpdateChecker] - setTimer")
		merlintimer.setUpdateTimer(self.checkForUpdates)

	def checkForUpdates(self):
		print("[MerlinUpdateChecker] - let's check for updates")
		self.remainingData = ""
		self.currentCommand = 0
		self.updatablePackagesList = []
		self.heldPackagesList = []
		self.newPackagesList = []
		self.removePackagesList = []
		self.autoremovePackagesList = []		
		self.errorList = []
		self.totalUpgrade = 0
		self.totalNew = 0
		self.totalHeld = 0
		self.totalRem = 0
		self.currentList = ""
		self.container = eConsoleAppContainer()
		self.appClosed_conn = self.container.appClosed.connect(self.commandFinished)
		self.dataAvail_conn = self.container.dataAvail.connect(self.readData)
		self.stdErrAvail_conn = self.container.stderrAvail.connect(self.getError)
	
		self.cmdList = ["apt-get update", "apt-get -s dist-upgrade"]	
		
		self.executeCommand()

	def executeCommand(self):
		self.container.execute(self.cmdList[self.currentCommand])
		
	def getError(self, error):
		self.errorList.append(str(error))
		print(error)

	def readData(self, data):
		#print data
		if self.currentCommand > 0:
			data = self.remainingData + data
			lines = data.split("\n")
			
			if len(lines[-1]):
				self.remainingData = lines[-1]
				lines = lines[0:-1]
			else:
				self.remainingData = ""
				
			i = 0
			
			for i in range(len(lines)):
				# it's a package
				if lines[i].startswith("  "):
					if self.currentList == "newPackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":						
								self.newPackagesList.append((line.strip(),))
					elif self.currentList == "heldPackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":						
								self.heldPackagesList.append((line.strip(),))
					elif self.currentList == "removePackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":
								self.removePackagesList.append((line.strip(),))
					elif self.currentList == "autoRemovePackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":
								self.autoremovePackagesList.append((line.strip(),))
					elif self.currentList == "updatablePackages":
						lineData = lines[i].split(" ")
						for line in lineData:
							if line != "":
								self.updatablePackagesList.append((line.strip(),))
					else:
						print("not a supported list")
				else:
					# it's a lead line
					if lines[i].startswith("The following NEW packages will be installed:"):
						self.currentList = "newPackages"
					elif lines[i].startswith("The following packages have been kept back:"):
						self.currentList = "heldPackages"
					elif lines[i].startswith("The following packages will be REMOVED:"):
						self.currentList = "removePackages"
					elif lines[i].startswith("The following packages were automatically installed and are no longer required:"):
						self.currentList = "autoRemovePackages"
					elif lines[i].startswith("The following packages will be upgraded:"):
						self.currentList = "updatablePackages"
					else:
						# todo: we actually only need the summary here
						updateSummaryCheck = updateSummary.match(lines[i])
						if updateSummaryCheck is not None:
							if len(updateSummaryCheck.groups()) == 4:
								self.totalUpgrade = updateSummaryCheck.groups()[0]
								self.totalNew = updateSummaryCheck.groups()[1]
								self.totalRem = updateSummaryCheck.groups()[2]
								self.totalHeld = updateSummaryCheck.groups()[3]	

	def commandFinished(self, retVal):
		print(retVal)
		
		if retVal == 0:
			if self.currentCommand == 0:
				# command is apt-get update
				self.currentCommand = 1
				self.executeCommand()
			else:
				print("up", self.totalUpgrade)
				print("new", self.totalNew)
				print("rem", self.totalRem)
				print("held", self.totalHeld)
				
				self.list = [(_("Upgradable"), self.totalUpgrade), (_("New"), self.totalNew), (_("Removable"), self.totalRem), (_("Kept back"), self.totalHeld) ]
				
				if self.totalUpgrade > 0 or self.totalNew > 0:
					print("[MerlinUpdateChecker] - Updates are available")
					Notifications.AddNotificationWithCallback(self.runUpgrade, MessageBox, _("Updates are available. Update now?"), MessageBox.TYPE_YESNO, 10, windowTitle="MerlinUpdateChecker", default=False, domain="MerlinUpdateChecker")
				merlintimer.cleanup()
				config.plugins.merlinupdatechecker.lastscantime.value = int(time())
				config.plugins.merlinupdatechecker.lastscantime.save()	
				
	def runUpgrade(self, result):
		if result:
			self.session.open(UpdatePlugin)	
		
merlinupdater = MerlinUpdater()