#
# ServiceRecordingSettings - this is a part of Merlin3-Image
#
# Coded by Dr.Best (c) 2013, part of Merlin3
# 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 enigma import eEnv, eServiceReference
from os import path as os_path
from pickle import load as pickle_load, dump as pickle_dump
from Components.config import config
from ServiceReference import ServiceReference


class ServiceRecordingSettings:
	instance = None
	def __init__(self):
		assert not ServiceRecordingSettings.instance, "only one ServiceRecordingSettings instance is allowed!"
		ServiceRecordingSettings.instance = self # set instance
		self.configfile = eEnv.resolve("${sysconfdir}/enigma2/servicerecordingsettings")
		self.data = self.__getRelationDict()

	def __getRelationDict(self):
		if os_path.exists(self.configfile):
			pkl_file = open(self.configfile, 'rb')
			if pkl_file:
				offsetdict = pickle_load(pkl_file)
				pkl_file.close()
				return offsetdict
		return {}

	def saveRelationDict(self, dict):
		pkl_file = open(self.configfile, 'wb')
		if pkl_file:
			pickle_dump(dict, pkl_file)
			pkl_file.close()
		self.data = dict


	def getMarginBefore(self, servicereference):
		if servicereference is not None:
			if not isinstance(servicereference, ServiceReference):
				serviceref = ServiceReference(servicereference)
			else:
				serviceref = servicereference
			before = self.data.get(serviceref.ref.toString(),None)
			if before is not None and before[1] != 99:
				return before[1] * 60
		return config.recording.margin_before.value * 60

	def getMarginAfter(self, servicereference):
		if servicereference is not None:
			if not isinstance(servicereference, ServiceReference):
				serviceref = ServiceReference(servicereference)
			else:
				serviceref = servicereference
			after = self.data.get(serviceref.ref.toString(),None)
			if after is not None and after[2] != 99:
				return after[2] * 60
		return config.recording.margin_after.value * 60
		
ServiceRecordingSettings()

