# Coded by Dream Elite Team

from Converter import Converter
from Components.Element import cached
from enigma import eTimer

class DEBlinker(Converter, object):

	def __init__(self, type):
		Converter.__init__(self, type)

		self.initial_instance_visible = True
		self.start_interval = 10000
		self.end_interval = 10000

		args = type.split(",")
		if "Invert" in args:
			self.initial_instance_visible = False
			args.pop(args.index("Invert"))
		if args and args != [""]:
			args = args[0].split(":")
			if len(args) > 1:
				if args[0].isdigit():
					self.start_interval = int(args[0]) * 1000
				if args[1].isdigit():
					self.end_interval = int(args[1]) * 1000
			else:
				if args[0].isdigit():
					self.start_interval = self.end_interval = int(args[0]) * 1000

		self.switch_interval = not(self.start_interval == self.end_interval)
		self.current_interval = self.start_interval

		self.poll_timer = eTimer()
		try:
			self.poll_timer_conn = self.poll_timer.timeout.connect(self.poll)
		except:
			self.poll_timer.callback.append(self.poll)

	def reuse(self):
		print "********** DEBlinker (reuse) visible: %s, start interval: %s, end interval: %s, switch interval: %s" % (str(self.initial_instance_visible), str(self.start_interval), str(self.end_interval), str(self.switch_interval))

	@cached
	def getText(self):
		try:
			text = self.source.text
		except:
			text = ""
		return text

	text = property(getText)

	def poll(self, poll_enabled = True, reset_visibility = False, what = None):
		if poll_enabled:
			if reset_visibility:
				instance_visible = self.initial_instance_visible
				self.current_interval = self.start_interval
			else:
				instance_visible = not self.downstream_elements[0].visible
				if self.switch_interval:
					self.current_interval = (self.current_interval == self.start_interval and self.end_interval) or self.start_interval
			self.changeVisibility(instance_visible, what)
			if reset_visibility or self.switch_interval:
				self.poll_timer.start(self.current_interval)
		else:
			self.poll_timer.stop()

	def doSuspend(self, suspended):
		if not suspended:
			self.poll(reset_visibility = True, what = (self.CHANGED_DEFAULT,))
		else:
			self.poll(poll_enabled = False)

	def doChangeVisibility(self, instance_visible):
		for downstream_element in self.downstream_elements:
			downstream_element.visible = instance_visible

	def changeVisibility(self, instance_visible, what):
		if what:
			if instance_visible:
				Converter.changed(self, what)
				self.doChangeVisibility(instance_visible)
			else:
				self.doChangeVisibility(instance_visible)
				Converter.changed(self, what)
		else:
			self.doChangeVisibility(instance_visible)

	def destroy(self):
		self.poll_timer.stop()
		try:
			del self.poll_timer_conn
		except:
			self.poll_timer.callback.remove(self.poll)

	def changed(self, what):
		if not self.suspended:
			if what[0] != self.CHANGED_POLL:
				self.poll(reset_visibility = True, what = what)
			else:
				Converter.changed(self, what)
