#  CaidDisplay - Converter
#
#  Coded by Dr.Best & weazle (c) 2010
#  Support: www.dreambox-tools.info
#
#  This plugin is licensed under the Creative Commons 
#  Attribution-NonCommercial-ShareAlike 3.0 Unported 
#  License. To view a copy of this license, visit
#  http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative
#  Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
#
#  Alternatively, this plugin may be distributed and executed on hardware which
#  is licensed by Dream Multimedia GmbH.

#  This plugin is NOT free software. It is open source, you are allowed to
#  modify it (if you keep the license), but it may not be commercially 
#  distributed other than under the conditions noted above.
#

from Components.Converter.Converter import Converter
from enigma import iServiceInformation, iPlayableService
from Components.Element import cached
from os.path import isfile
from Poll import Poll

class MetrixCaidDisplay(Poll, Converter, object):

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

		self.VERTICAL = "Vertical" in type

		self.ecm_info = {}
		self.systemCaids = {
			"01" : "Seca            ",
			"05" : "Via        ",
			"06" : "Ird       ",
			"09" : "NDS            ",
			"0B" : "Conax               ",
			"0D" : "CW           ",
			"17" : "BC         ",
			"18" : "Nagra              " }

		self.poll_interval = 5000
		self.poll_enabled = True

	@cached
	def get_caidlist(self):
		caidlist = {}
		service = self.source.service
		if service:
			info = service and service.info()
			if info:        
				caids = info.getInfoObject(iServiceInformation.sCAIDs)
				if caids:
					for cs in self.systemCaids:
						caidlist[cs] = (self.systemCaids.get(cs),0)
					for caid in caids:
						c = "%x" % int(caid)
						if len(c) == 3:
							c = "0%s" % c
						c = c[:2].upper()
						if self.systemCaids.has_key(c):
							caidlist[c] = (self.systemCaids.get(c),1)
					ecm_info = self.ecm_info
					if ecm_info:
						emu_caid = ecm_info.get("caid", "")
						if emu_caid and emu_caid != "0x000":
							c = emu_caid.lstrip("0x")
							if len(c) == 3:
								c = "0%s" % c
							c = c[:2].upper()
							caidlist[c] = (self.systemCaids.get(c),2)
		return caidlist

	getCaidlist = property(get_caidlist)

	@cached
	def getText(self):
		if self.VERTICAL:
			textvalue = "\n    Free to air"
		else:
			textvalue = ""
		service = self.source.service
		if service:
			info = service and service.info()
			if info:
				if info.getInfoObject(iServiceInformation.sCAIDs):
					textvalue = ""
					ecm_info = self.ecm_info
					if ecm_info:
						# caid
						caid = ecm_info.get("caid", "")
						caid = caid.lstrip("0x")
						caid = caid.upper()
						caid = caid.zfill(4)
						# hops
						hops = ecm_info.get("hops", None)
						# ecm time	
						ecm_time = ecm_info.get("ecm time", None)
						if ecm_time:
							if "msec" in ecm_time:
								ecm_time = "%s" % ecm_time
							elif ecm_time != "nan":
								ecm_time = "%s s" % ecm_time
							else:
								ecm_time = ""
						# using	
						using = ecm_info.get("using", "")	# emu cccam
						# protocol
						protocol = ecm_info.get("protocol", None)	# emu oscam
						if using:
							# emu cccam
							# provid
							provid = ecm_info.get("provid", "")
							provid = provid.lstrip("0x")
							provid = provid.upper()
							provid = provid.zfill(6)
							# pid
							pid = ecm_info.get("pid", "")
							pid = pid.lstrip("0x")
							pid = pid.upper()
							pid = pid.zfill(4)
							# address
							address = ecm_info.get("address", "")
							if address:
								if address == "/dev/sci0":
									address = "Slot #1"
								elif address == "/dev/sci1":
									address = "Slot #2"
								elif address.find("/dev/ttyUSB") >= 0:
									address = "USB Reader"
							if using == "emu":
								if self.VERTICAL:
									textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nECM Time: %s" % (caid, provid, pid, ecm_time)
								else:
									textvalue = "CCcam decode: %s@%s - ECM: %s" % (caid, provid, ecm_time)
							elif using == "CCcam-s2s":
								if hops and hops != "0":
									if self.VERTICAL:
										textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nFrom: %s\nHops: %s\nECM Time: %s" % (caid, provid, pid, address, hops, ecm_time)		
									else:
										textvalue = "CCcam decode: %s@%s - From: %s - Hops: %s - ECM: %s" % (caid, provid, address, hops, ecm_time)		
								else:
									if self.VERTICAL:
										textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nFrom: %s\nECM Time: %s" % (caid, provid, pid, address, ecm_time)
									else:
										textvalue = "CCcam decode: %s@%s - From: %s - ECM: %s" % (caid, provid, address, ecm_time)
							else:
								if self.VERTICAL:
									textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nFrom: %s\nECM Time: %s" % (caid, provid, pid, address, ecm_time)		
								else:
									textvalue = "CCcam decode: %s@%s - From: %s - ECM: %s" % (caid, provid, address, ecm_time)		
						elif protocol:
							# emu oscam
							# reader
							reader = ecm_info.get("reader", None)
							# prov
							prov = ecm_info.get("prov", "")
							prov = prov.lstrip("0x")
							prov = prov.upper()
							prov = prov.zfill(6)
							# pid
							pid = ecm_info.get("pid", "")
							pid = pid.lstrip("0x")
							pid = pid.upper()
							pid = pid.zfill(4)
							# from
							oscsource = ecm_info.get("from", None) 
							if protocol == "internal":
								oscsource = "Internal Slot"
							elif protocol in ("smartreader","mouse","serial","pcsc","sc8in1","smargo"):
								oscsource = "USB Slot"
							if oscsource: 
								if hops and hops != "0":
									if self.VERTICAL:
										textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nFrom: %s\nHops: %s\nECM Time: %s" % (caid, prov, pid, oscsource, hops, ecm_time)
									else:
										textvalue = "OScam decode: %s@%s - From: %s - Hops: %s - ECM: %s" % (caid, prov, oscsource, hops, ecm_time)
								else:
									if self.VERTICAL:
										textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nReader: %s\nFrom: %s\nECM Time: %s" % (caid, prov, pid, reader, oscsource, ecm_time)
									else:
										textvalue = "OScam decode: %s@%s - Reader: %s - From: %s - ECM: %s" % (caid, prov, reader, oscsource, ecm_time)
							else:
								if self.VERTICAL:
									textvalue = "CaID: 0x%s\nProvID: 0x%s\nECMPid: 0x%s\nECM Time: %s" % (caid, prov, pid, ecm_time)
								else:
									textvalue = "OScam decode: %s@%s - ECM: %s" % (caid, prov, ecm_time)
					else:
						if self.VERTICAL:
							textvalue = "\n    Unable to decode\n    or no decoding info."
						else:
							textvalue = "Unable to decode or no decoding info"
		return textvalue 

	text = property(getText)

	def ecmfile(self):
		ecm = None
		info = {}
		service = self.source.service
		if service:
			frontendInfo = service.frontendInfo()
			if frontendInfo:
				try:
					ecm = open("/tmp/ecm.info", "rb").readlines()
				except:
					pass
			if ecm:
				for line in ecm:
					x = line.lower().find("msec")
					if x != -1:
						info["ecm time"] = line[0:x+4]
					elif line.lower().find("response:") != -1:
						y = line.lower().find("response:")
						if y != -1:
							info["ecm time"] = line[y+9:].strip("\n\r")
					else:
						item = line.split(":", 1)
						if len(item) > 1:
							info[item[0].strip().lower()] = item[1].strip()
						else:
							if not info.has_key("caid"):
								x = line.lower().find("caid")
								if x != -1:
									y = line.find(",")
									if y != -1:
										info["caid"] = line[x+5:y]
		return info

	def changed(self, what):
		#if (what[0] == self.CHANGED_SPECIFIC and what[1] == iPlayableService.evUpdatedInfo) or what[0] == self.CHANGED_POLL:
		if what[0] == self.CHANGED_SPECIFIC or what[0] == self.CHANGED_POLL:
			self.ecm_info = self.ecmfile()
			Converter.changed(self, what)