from enigma import eServiceCenter, eServiceReference
from Components.config import config

class StreamRelay(object):
	def __init__(self):
		self.srip = config.merlin2.streamrelayip.value
		self.srport = config.merlin2.streamrelayport.value
		
	def updateServerSettings(self):
		self.srip = config.merlin2.streamrelayip.value
		self.srport = config.merlin2.streamrelayport.value

	def checkStreamRelay(self,ref):
		print "[MerlinFunctions] - Check StreamRelay"
		
		if self.isStreamRelay(ref):
			ref.flags = 0
			info = eServiceCenter.getInstance().info(ref)
			sname = info.getName(ref).replace('\xc2\x86', '').replace('\xc2\x87', '')
			ref.setName(sname)
			ref.setPath("http://%s:%d/%s" %(".".join(str(x) for x in self.srip), self.srport, ref.toString()))
			ref.setUnsignedData(4, 33)
			ref.flags = 256
		return ref
		
	def removeStreamRelay(self, ref):
		print "[MerlinFunctions] - Remove StreamRelay"
		if ref and ref.getUnsignedData(4) == 33:
			if ref.getPath():
				path = ref.getPath()
				pos = path.rfind("/")
				if pos != 1:
					srefstr = path[pos+1:]
					sref = eServiceReference(srefstr)
					namespace = sref.getUnsignedData(4)
					
					ref.setUnsignedData(4, namespace)
					ref.flags = 512
					ref.setName("")
					ref.setPath("")
		return ref
		
	def isStreamRelay(self, ref):
		return ref and ref.flags & 512
		
	def toggleStreamRelay(self,ref):
		print "[MerlinFunctions] - Toggle StreamRelay"
		if self.isStreamRelay(ref):
			ref.flags = 0
		elif ref:
			ref.flags = 512
			
		return ref
			
			
		
		