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

feSatellite = iDVBFrontend.feSatellite
feCable = iDVBFrontend.feCable
feTerrestrial = iDVBFrontend.feTerrestrial 

class MetrixFrontendInfo(Converter, object):

	BER = 0
	SNR = 1
	AGC = 2
	LOCK = 3
	SNRdB = 4
	SLOT_NUMBER = 5
	TUNER_TYPE = 6

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

		self.type = {	"BER": 			self.BER,
						"SNR":			self.SNR,
						"AGC":			self.AGC,
						"LOCK":			self.LOCK,
						"SNRdB":		self.SNRdB,
						"SlotNumber":	self.SLOT_NUMBER,
						"TunerType":	self.TUNER_TYPE,
					}[type] 

	@cached
	def getText(self):
		percent = None
		if self.type == self.BER: # as count
			count = self.source.ber
			if count is not None:
				return 	"BER: %d" % (count)
			return "BER: N/A"
		elif self.type == self.SNR:
			percent = self.source.snr
			if percent is not None:
				return "SNR: %d%%" % (percent * 100 / 65536)
			return "SNR: N/A"
		elif self.type == self.AGC:
			percent = self.source.agc
			if percent is not None:
				return "AGC: %d%%" % (percent * 100 / 65536)
			return "AGC: N/A"
		elif self.type == self.SNRdB:
			if self.source.snr_db is not None:
				return "SNRdB: %3.02f dB" % (self.source.snr_db / 100.0)
			elif self.source.snr is not None: #fallback to normal SNR...
				return "SNR: %d%%" % (self.source.snr * 100 / 65536)
			return "SNRdB: N/A"
		elif self.type == self.TUNER_TYPE:
			frontend_type = self.source.frontend_type
			if frontend_type == feSatellite:
				return "DVB-S"
			elif frontend_type == feTerrestrial:
				return "DVB-T"
			elif frontend_type == feCable:
				return "DVB-C"
			return ""
		return ""

	text = property(getText)

	@cached
	def getBool(self):
		if self.type == self.LOCK:
			lock = self.source.lock
			if lock is None:
				lock = False
			return lock
		elif self.type == self.BER:
			ber = self.source.ber
			if ber is None:
				ber = 0
			return ber > 0
		return False

	boolean = property(getBool)

	@cached
	def getValue(self):
		if self.type == self.BER:
			if self.source.ber < self.range:
				return self.source.ber or 0
			else:
				return self.range
		elif self.type == self.SNR:
			return self.source.snr or 0
		elif self.type == self.AGC:
			return self.source.agc or 0
		elif self.type == self.TUNER_TYPE:
			return self.source.frontend_type
		elif self.type == self.SLOT_NUMBER:
			num = self.source.slot_number
			return num is None and -1 or num
		return 0

	range = 65536
	value = property(getValue)