from Screens.Screen import Screen
from enigma import ePoint, eSize, eServiceCenter, getBestPlayableServiceReference, eServiceReference
from Components.MerlinVideoWidget import MerlinVideoWidget
from Components.config import config, ConfigPosition
from enigma import getDesktop

class PictureInPicture(Screen):
	def __init__(self, session):
		Screen.__init__(self, session)
		self["video"] = MerlinVideoWidget()
		self.currentService = None
		self.onLayoutFinish.append(self.LayoutFinished)

	def LayoutFinished(self):
		self.onLayoutFinish.remove(self.LayoutFinished)
		self["video"].scaleToWidget(1)
		x = config.merlin2.pip.value[0]
		y = config.merlin2.pip.value[1]
		w = config.merlin2.pip.value[2]
		h = config.merlin2.pip.value[3]
		if x != -1 and y != -1 and w != -1 and h != -1:
			self.move(x, y)
			self.resize(w, h)

	def move(self, x, y):
		config.merlin2.pip.value[0] = x
		config.merlin2.pip.value[1] = y
		config.merlin2.pip.save()
		self.instance.move(ePoint(x, y))

	def resize(self, w, h):
		config.merlin2.pip.value[2] = w
		config.merlin2.pip.value[3] = h
		config.merlin2.pip.save()
		self.instance.resize(eSize(*(w, h)))
		self["video"].instance.resize(eSize(*(w, h)))

	def getPosition(self):
		return ((self.instance.position().x(), self.instance.position().y()))

	def getSize(self):
		return (self.instance.size().width(), self.instance.size().height())

	def playService(self, service):
		if service and (service.flags & eServiceReference.isGroup):
			ref = getBestPlayableServiceReference(service, eServiceReference())
		else:
			ref = service
		ref = self.checkStreamRelay(ref)
		if ref:
			self.pipservice = None
			self["video"].playVideo(ref)
			self.currentService = service
			return True
		return False

	def getCurrentService(self):
		return self.currentService

	def checkStreamRelay(self, ref):
		if ref and ref.flags & 512:
			import subprocess
			ipaddress = subprocess.check_output(["hostname", "-i"])
			ref.flags = 0
			info = self.ServiceHandler.info(ref)
			sname = info.getName(ref).replace('\xc2\x86', '').replace('\xc2\x87', '')
			ref.setName(sname)
			ref.setPath("http://%s:17999/%s" %(ipaddress.strip(), ref.toString()))
			ref.setUnsignedData(4, 33)
			ref.flags = 256
		return ref