#
# ServiceRecordingSettingsSetup - this is a part of Merlin3-Image
#
# Coded by Dr.Best (c) 2012
# Support: www.dreambox-tools.info
# E-Mail: dr.best@dreambox-tools.info
#
# This plugin is open source but it is NOT free software.
#
# This plugin may only be distributed to and executed on hardware which
# is licensed by Dream Multimedia GmbH.
# In other words:
# It's NOT allowed to distribute any parts of this plugin or its source code in ANY way
# to hardware which is NOT licensed by Dream Multimedia GmbH.
# It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way
# on hardware which is NOT licensed by Dream Multimedia GmbH.
#
# If you want to use or modify the code or parts of it,
# you have to keep MY license and inform me about the modifications by mail.
#

from __future__ import print_function
from __future__ import absolute_import
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from enigma import eServiceReference, eListboxPythonMultiContent, gFont, RT_HALIGN_LEFT, RT_VALIGN_CENTER
from Components.MenuList import MenuList
from Components.Sources.StaticText import StaticText
from Components.ActionMap import ActionMap
from ServiceReference import ServiceReference
from Components.ConfigList import ConfigListScreen
from Components.config import getConfigListEntry, config, NoSave, ConfigSelection, ConfigDirectory, ConfigNumber

from os import path as os_path
from pickle import load as pickle_load, dump as pickle_dump
from enigma import eEnv



from Components.UsageConfig import defaultMoviePath, defaultStorageDevice
from Screens.ChannelSelection import SimpleChannelSelection
from Components.ServiceRecordingSettings import ServiceRecordingSettings
from Screens.LocationBox import MovieLocationBox
from skin import TemplatedListFonts, componentSizes

class ServiceRecordingSettingsSetup(Screen):
	skin = """
		<screen name="ServiceRecordingSettingsSetup" position="center,center" size="655,400">
			<widget render="Label" source="name" position="5,0" size="320,50" font="Regular;20" halign="left"/>
			<widget render="Label" source="relationname" position="330,0" size="320,50" font="Regular;20" halign="left"/>
			<widget name="entrylist" position="0,50" size="655,300" scrollbarMode="showOnDemand"/>
			<widget render="Label" source="key_red" position="0,350" size="140,40" zPosition="5" valign="center" halign="center" backgroundColor="red" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget source="key_green" render="Label" position="140,350" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget render="Label" source="key_yellow" position="280,350" size="140,40" zPosition="5" valign="center" halign="center" backgroundColor="yellow" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget render="Label" source="key_blue" position="420,350" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<ePixmap position="0,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
			<ePixmap position="140,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
			<ePixmap position="280,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
			<ePixmap position="420,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
		</screen>"""

	def __init__(self, session):
		Screen.__init__(self, session)
		self.title = _("ServiceRecordingSettings - Config")
		self["name"] = StaticText(_("Service"))
		self["relationname"] = StaticText(_("Default location"))
		self["key_red"] = StaticText(_("Delete"))
		self["key_green"] = StaticText(_("Close"))
		self["key_yellow"] = StaticText(_("Add"))
		self["key_blue"] = StaticText(_("Edit"))
		self["entrylist"] = ServiceRecordingSettingsEntryList([])
		self["actions"] = ActionMap(["WizardActions","MenuActions","ShortcutActions"],
			{
			 "ok"	:	self.keyBlue,
			 "back"	:	self.keyClose,
			 "red"	:	self.keyDelete,
			 "green":	self.keyClose,
			 "yellow":	self.keyYellow,
			 "blue": 	self.keyBlue,
			 }, -1)
		self.updateList()

	def updateList(self):
		self["entrylist"].buildList()

	def keyClose(self):
		self.close()

	def keyBlue(self):
		try:sel = self["entrylist"].l.getCurrentSelection()[0]
		except: sel = None
		if sel is None:
			return
		self.session.openWithCallback(self.updateList,ServiceRecordingSettingsEntryConfigScreen,sel)

	def keyYellow(self):
		self.session.openWithCallback(self.updateList,ServiceRecordingSettingsEntryConfigScreen,None)

	def keyDelete(self):
		try:sel = self["entrylist"].l.getCurrentSelection()[0]
		except: sel = None
		if sel is None:
			return
		self.session.openWithCallback(self.deleteConfirm, MessageBox, _("Do you really want to delete this entry?"))

	def deleteConfirm(self, result):
		if not result:
			return
		sel = self["entrylist"].l.getCurrentSelection()[0]
		del self["entrylist"].configSMP[sel[0]]
		ServiceRecordingSettings.instance.saveRelationDict(self["entrylist"].configSMP)
		self.updateList()


class ServiceRecordingSettingsEntryConfigScreen(ConfigListScreen, Screen):
	skin = """
		<screen name="ServiceRecordingSettingsEntryConfigScreen" position="center,center" size="600,400">
			<widget name="config" position="20,10" size="570,330" scrollbarMode="showOnDemand" />
			<ePixmap position="0,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
			<ePixmap position="140,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
			<ePixmap position="280,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
			<ePixmap position="420,350" zPosition="4" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
			<widget source="key_red" render="Label" position="0,350" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			<widget source="key_green" render="Label" position="140,350" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
		</screen>"""

	def __init__(self, session, entry):	
		self.session = session
		Screen.__init__(self, session)
		self.title = _("ServiceRecordingSettings - Entry Config")
		self["actions"] = ActionMap(["SetupActions", "ColorActions"],
		{
			"green": self.keySave,
			"red": self.keyCancel,
			"cancel": self.keyCancel,
			"ok": self.keySelect,
		}, -2)
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("OK"))
		self.configSMP = ServiceRecordingSettings.instance.data
		self.entry = entry
		default = defaultMoviePath()
		tmp = config.movielist.videodirs.value
		if default not in tmp:
			tmp.append(default)
		if entry is None:
			self.currentKey = None
			self.ref =  NoSave(ConfigDirectory(default = _("Press OK to select a service")))
			self.dirname = ConfigSelection(default = default, choices = tmp)
			self.marginbefore = ConfigNumber(default=99)
			self.marginafter = ConfigNumber(default=99)
		else:
			self.currentKey = entry[0]
			self.ref =  NoSave(ConfigDirectory(default = ServiceReference(eServiceReference(entry[0])).getServiceName()))
			path = entry[1][0]		
			if path is not None and path not in tmp:
				tmp.append(path)
			self.dirname = ConfigSelection(default = path, choices = tmp)
			self.marginbefore = ConfigNumber(default=entry[1][1])
			self.marginafter = ConfigNumber(default=entry[1][2])
		self.list = [ ]
		self.serviceref =  getConfigListEntry(_("Service"), self.ref)
		self.recordpath =  getConfigListEntry(_("Location"), self.dirname)
		self.recordingmarginbefore = getConfigListEntry(_("Margin before record (minutes, 99 = master setting)"), self.marginbefore)
		self.recordingmarginafter = getConfigListEntry(_("Margin after record"), self.marginafter)
		self.list.append(self.serviceref)
		self.list.append(self.recordpath)
		self.list.append(self.recordingmarginbefore)
		self.list.append(self.recordingmarginafter)
		ConfigListScreen.__init__(self, self.list, session)
		
	def keySelect(self):
		cur = self["config"].getCurrent()
		if cur == self.serviceref:
			self.session.openWithCallback(self.channelSelected, SimpleChannelSelection, _("Channel Selection"))
		elif cur == self.recordpath:
			self.session.openWithCallback(self.pathSelected,MovieLocationBox,_("Choose target folder"), self.dirname.value, minFree = 100)

	def channelSelected(self, ref = None):
		if ref:
			self.entry = (ref.toString(), self.dirname.value, self.marginbefore.value, self.marginafter.value)
			self.ref.value = ServiceReference(ref).getServiceName()

	def pathSelected(self, res):
		if res is not None:
			if config.movielist.videodirs.value != self.dirname.choices:
				self.dirname.setChoices(config.movielist.videodirs.value, default=res)

			if self.entry:
				val1 = self.entry[0]
			else:
				val1 = None
			self.entry = (val1, res, self.marginbefore.value, self.marginafter.value)
			self.dirname.value = res

	def keySave(self):
		if self.entry and self.entry[0] and self.entry[1]:
			if self.currentKey is not None:
				del self.configSMP[self.currentKey]
			self.configSMP[self.entry[0]] = (self.dirname.value, self.marginbefore.value, self.marginafter.value)
			ServiceRecordingSettings.instance.saveRelationDict(self.configSMP)
			print(ServiceRecordingSettings.instance.data)
		self.close()

	def keyCancel(self):
		ConfigListScreen.cancelConfirm(self, True)

class ServiceRecordingSettingsEntryList(MenuList):
	SKIN_COMPONENT_KEY = "MerlinServiceRecordingList"
	SKIN_COMPONENT_DIR_WIDTH = "dirWidth"
	SKIN_COMPONENT_TEXT_HEIGHT = "textHeight"
	SKIN_COMPONENT_LINE_SPACING = "lineSpacing"
	
	def __init__(self, list, enableWrapAround = True):
		MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
		tlf = TemplatedListFonts()
		self.l.setFont(0, gFont(tlf.face(tlf.MEDIUM), tlf.size(tlf.MEDIUM)))
		self.l.setFont(1, gFont(tlf.face(tlf.SMALL), tlf.size(tlf.SMALL)))
		self.configSMP = None

	def postWidgetCreate(self, instance):
		MenuList.postWidgetCreate(self, instance)
		instance.setItemHeight(componentSizes.itemHeight(self.SKIN_COMPONENT_KEY, 65))

	def getCurrentIndex(self):
		return self.instance.getCurrentIndex()
		
	def buildList(self):
		self.configSMP = ServiceRecordingSettings.instance.data
		list_smp = []
		
		sizes = componentSizes[ServiceRecordingSettingsEntryList.SKIN_COMPONENT_KEY]
		configEntryWidth = sizes.get(componentSizes.ITEM_WIDTH, 640)
		dirWidth = sizes.get(ServiceRecordingSettingsEntryList.SKIN_COMPONENT_DIR_WIDTH, 330)
		textHeight = sizes.get(ServiceRecordingSettingsEntryList.SKIN_COMPONENT_TEXT_HEIGHT, 20)
		lineSpacing = sizes.get(ServiceRecordingSettingsEntryList.SKIN_COMPONENT_LINE_SPACING, 22)
				
		for c in list(self.configSMP.items()):
			if c[1][1] == 99:
				display1 = _("using master setting (%d minutes)") % config.recording.margin_before.value
			else:
				display1 = _("individual setting (%d minutes)") % c[1][1]
			if c[1][2] == 99:
				display2 = _("using master setting (%d minutes)") % config.recording.margin_after.value
			else:
				display2 = _("individual setting (%d minutes)") % c[1][2]
			res = [
				c,
				(eListboxPythonMultiContent.TYPE_TEXT, 5, 2, dirWidth-10, textHeight, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, ServiceReference(eServiceReference(c[0])).getServiceName()),
				(eListboxPythonMultiContent.TYPE_TEXT, dirWidth, 2 ,configEntryWidth, textHeight, 0, RT_HALIGN_LEFT|RT_VALIGN_CENTER, c[1][0]),
				(eListboxPythonMultiContent.TYPE_TEXT, 5, lineSpacing,configEntryWidth, textHeight, 1, RT_HALIGN_LEFT|RT_VALIGN_CENTER, _("Margin before record: ") + display1),
				(eListboxPythonMultiContent.TYPE_TEXT, 5, lineSpacing+lineSpacing,configEntryWidth, textHeight, 1, RT_HALIGN_LEFT|RT_VALIGN_CENTER, _("Margin after record: ") + display2),

			]
			list_smp.append(res)
		self.list = list_smp
		self.l.setList(list_smp)
		self.moveToIndex(0)

