from Components.Task import PythonTask, Task, Job, job_manager
from Tools.Directories import fileExists
from enigma import eTimer
from os import path




class HLSDownloadJob(Job):
	def __init__(self, url, destfile, name):
		Job.__init__(self, _("HLS download"))
		cmdline = '/usr/bin/gst-launch-1.0 "%s" !  hlsdemux ! filesink location="%s"'%(url,destfile)
		#cmdline = 'mv -f "%s" "%s"' % (url,destfile)
		AddHLSProcessTask(self, cmdline, url, destfile, name)

class AddHLSProcessTask(Task):
	def __init__(self, job, cmdline, url, destfile, name):
		Task.__init__(self, job, name)
		self.setCmdline(cmdline)
		self.url = url
		self.destfile = destfile

		self.ProgressTimer = eTimer()
		self.ProgressTimer.callback.append(self.ProgressUpdate)

	def ProgressUpdate(self):
		if self.srcsize <= 0 or not fileExists(self.destfile, 'r'):
			return

		self.setProgress(int((path.getsize(self.destfile)/float(self.srcsize))*100))
		self.ProgressTimer.start(5000, True)

	def prepare(self):
		#if fileExists(self.url, 'r'):
		self.srcsize = 0 #path.getsize(self.url)
		self.ProgressTimer.start(5000, True)

	def afterRun(self):
		self.setProgress(100)
		self.ProgressTimer.stop()


