from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Sources.Progress import Progress
from Components.Sources.StaticText import StaticText
from Screens.MessageBox import MessageBox
from Tools.Directories import fileExists
from Tools.Downloader import downloadWithProgress
from enigma import eTimer

from os import remove

MSG_ABORTED = _("Download of file:\n%s\ncanceled by user!")
MSG_COMPLETED = _("Download of file:\n%s\ncompleted")
MSG_FAILED = _("Download of file:\n%s\nfailed with error: %s")

STATUS_ABORTED = -1
STATUS_DONE = 1
STATUS_FAILED = 0

class SatLodgeDownloader(Screen):
	skin ="""
	    <screen name="SatLodgeDownloader" position="390,200" size="500,190">
        <!--ePixmap pixmap="skin_default/progress_bg.png" position="10,17" size="480,24" zPosition="-1" transparent="1" /-->
        <widget source="progressbar" render="Progress" position="10,20" size="480,18" zPosition="1" transparent="1" />
        <widget name="filename" position="10,55" size="480,40" font="Regular;20" halign="center" valign="center" foregroundColor="white" />
        <widget name="status" position="10,100" size="480,30" font="Regular;18" halign="center" valign="center" foregroundColor="white" />
        <eLabel position="0,149" size="500,2" backgroundColor="grey" zPosition="5" />
    </screen> """

	IS_DIALOG = True

	RETURN_STATUS = STATUS_FAILED

	def __init__(self, session, url, folder, filename):
		Screen.__init__(self, session)
		self.url = url
		self.filename = filename
		self.destination = folder + filename
		self["filename"] = Label("")
		self["status"] = Label("")
		self["progressbar"] = Progress(value = 0, range = 1000)
		self["actions"] = ActionMap(["OkCancelActions"],
		{
			"cancel": self.abort,
		}, -1)
		self.lastReceivedBytes = 0
		self.startDownloadTimer = eTimer()
		self.startDownloadTimer_conn = self.startDownloadTimer.timeout.connect(self.fileDownload)
		self.download = None
		self.stopped = False
		self.onLayoutFinish.append(self.layoutFinished)

	def layoutFinished(self):
		self.setTitle(_("Downloading..."))
		self.startDownload()

	def startDownload(self):
		self["progressbar"].value = 0
		self.startDownloadTimer.start(200, True)

	def fileDownload(self):
		print "[SatLodgeDownloader] Downloading %s to %s" % (self.url, self.destination)
		self["filename"].setText(_("Downloading file:\n%s") % self.filename)
		self.download = downloadWithProgress(self.url, self.destination)
		self.download.addProgress(self.progress)
		self.download.start().addCallbacks(self.finished, errback = self.failed)

	def progress(self, receivedbytes, totalbytes):
		if receivedbytes - self.lastReceivedBytes > 10240:
			print "[SatLodgeDownloader] Downloading..."
			self["progressbar"].value = int(1000 * (float(receivedbytes) / float(totalbytes)))
			self["status"].setText(_("Downloaded %d of %d KBytes") % (receivedbytes / 1024, totalbytes / 1024))
			self.lastReceivedBytes = receivedbytes

	def finished(self, result = None):
		print "[SatLodgeDownloader] Download finished"
		self.RETURN_STATUS = STATUS_DONE
		self["progressbar"].value = 1000
		self["filename"].setText(_("Finished downloading of file:\n%s") % self.filename)
		self["status"].setText(_("Download finished"))
		msg = MSG_COMPLETED % self.filename
		self.session.openWithCallback(self.exit, MessageBox, msg, MessageBox.TYPE_INFO, windowTitle = _("Download finished"), timeout=5, close_on_any_key = True)

	def failed(self, failure_instance = None, error_message = ""):
		if self.stopped:
			self.stoppedByUser()
			return
		if error_message == "" and failure_instance is not None:
			error_message = failure_instance.getErrorMessage()
		print "[SatLodgeDownloader] Download failed with error:", error_message
		self.RETURN_STATUS = STATUS_FAILED
		self.removeDestination()
		self["filename"].setText(_("Failed downloading of file:\n%s") % self.filename)
		self["status"].setText(_("Download failed with error: %s") % error_message)
		msg = MSG_FAILED % (self.filename, error_message)
		self.session.openWithCallback(self.exit, MessageBox, msg, MessageBox.TYPE_ERROR, windowTitle = _("Download failed"), timeout=5, close_on_any_key = True)

	def stoppedByUser(self):
		self.RETURN_STATUS = STATUS_ABORTED
		self.removeDestination()
		self["filename"].setText(_("Canceled downloading of file:\n%s") % self.filename)
		self["status"].setText(_("Download canceled by user!"))
		msg = MSG_ABORTED % self.filename
		self.session.openWithCallback(self.exit, MessageBox, msg, MessageBox.TYPE_WARNING, windowTitle = _("Download canceled"), timeout=5, close_on_any_key = True)

	def abort(self):
		print "[SatLodgeDownloader] Download canceled"
		if self.download:
			self.stopped = True
			self.download.stop()

	def removeDestination(self):
		if fileExists(self.destination):
			remove(self.destination)

	def exit(self, retval = True):
		self.download = None
		self.startDownloadTimer = None
		self.close(self.RETURN_STATUS)
