from __future__ import absolute_import
from Screens.ChannelSelection import ChannelSelectionRadio, SelectionEventInfo
from Screens.InfoBarGenerics import NumberZap
from Screens.Screen import Screen
from enigma import eServiceReference, eServiceCenter
from Components.config import config

class MerlinChannelSelectionRadio(ChannelSelectionRadio, SelectionEventInfo):
	def __init__(self, session, infobar=None):
		ChannelSelectionRadio.__init__(self, session, infobar)
		SelectionEventInfo.__init__(self)
		self.skinName = "ChannelSelectionRadio"

	def createSummary(self):
		return MerlinChannelSelectionRadioSummary

	def keyNumberGlobal(self, number):
		if number != 0:
			self.session.openWithCallback(self.numberEntered, NumberZap, number)

	def numberEntered(self, retval):
		if retval > 0:
			self.zapToNumber(retval)

	def searchNumberHelper(self, serviceHandler, num, bouquet):
		servicelist = serviceHandler.list(bouquet)
		if not servicelist is None:
			while num:
				serviceIterator = servicelist.getNext()
				if not serviceIterator.valid():
					break
				playable = not (serviceIterator.flags & (eServiceReference.isMarker|eServiceReference.isDirectory))
				if playable:
					num -= 1;
			if not num:
				return serviceIterator, 0
		return None, num

	def zapToNumber(self, number):
		bouquet = self.bouquet_root
		service = None
		serviceHandler = eServiceCenter.getInstance()
		if not config.usage.multibouquet.value:
			service, number = self.searchNumberHelper(serviceHandler, number, bouquet)
		else:
			bouquetlist = serviceHandler.list(bouquet)
			if not bouquetlist is None:
				while number:
					bouquet = bouquetlist.getNext()
					if not bouquet.valid():
						break
					if bouquet.flags & eServiceReference.isDirectory:
						service, number = self.searchNumberHelper(serviceHandler, number, bouquet)
		if not service is None:
			if self.getRoot() != bouquet:
				self.clearPath()
				if self.bouquet_root != bouquet:
					self.enterPath(self.bouquet_root)
				self.enterPath(bouquet)
			self.setCurrentSelection(service)
			self.channelSelected()

class MerlinChannelSelectionRadioSummary(Screen):
	def __init__(self, session, parent):
		Screen.__init__(self, session, parent)
		self["RdsDecoder"] = parent.info["RdsDecoder"]
		self.onClose.append(self.__onClose)
		self.skinName = ["MerlinChannelSelectionRadioSummary", "ChannelSelectionRadio_summary"]

	def __onClose(self):
		del self["RdsDecoder"]
