# -*- coding: utf-8 -*-
from gLocale import _
from GeminiDef import *
from gTools import libgeminimain, cleanexit, pathExists, pathRemove, getAspectforPic, gLoadPixmap
from lib.libpicview import ePicViewer
from plugin import cgevent
from WidgetTools import setFullPixmap
from ThumbView import CThumbView, ConfThumbView, getBrowserColor

from enigma import ePicLoad, eTimer, getDesktop, gPixmapPtr, eSize

from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.HelpMenu import HelpableScreen
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.Pixmap import Pixmap, MultiPixmap
from Components.Label import Label
from Components.Sources.StaticText import StaticText
from skin import parseColor
from Tools.BoundFunction import boundFunction

from os import path as os_path

#Wie drehen
ROTATE_EXIF=0
FLIP_HOR=2
ROTATE_180=3
FLIP_VER=4
ROTATE_90=6
ROTATE_270=8

TMPPICTURE="/tmp/WidgetShowPic.jpg"

class WidgetShowPic(Screen):
	
	def __init__(self, session , file, cleartmp=True, setfilename=None):
		size_w = getDesktop(0).size().width()
		size_h = getDesktop(0).size().height()
		space = cgevent.getConfig("gpicplayer_space",30)
		
		self.__resizetype=2#fast accel
		self.__maxwidth=size_w-(space*2)
		self.__maxheight=size_h-(space*2)
		if self.__maxwidth > 1750:
			self.__resizetype=1#color resize

		self.__bgcolor,self.__fgcolor = getBrowserColor()
		
		self.skin = "<screen position=\"0,0\" size=\"" + str(size_w) + "," + str(size_h) + "\" flags=\"wfNoBorder\" > \
			<widget name=\"BGlabel\" position=\"0,0\" zPosition=\"0\" size=\""+ str(size_w) + "," + str(size_h) + "\" /><widget name=\"pic\" position=\"" + str(space) + "," + str(space) + "\" size=\"" + str(size_w-(space*2)) + "," + str(size_h-(space*2)) + "\" zPosition=\"1\" alphatest=\"on\" /> \
			<widget name=\"point\" position=\""+ str(space+5) + "," + str(space+2) + "\" size=\"22,22\" zPosition=\"2\" alphatest=\"blend\" /> \
			<widget name=\"file\"  position=\""+ str(space+45) + "," + str(space) + "\" size=\""+ str(size_w-(space*2)-50) + ",25\" font=\"Regular;18\" zPosition=\"2\" noWrap=\"1\" transparent=\"1\" /></screen>"

		Screen.__init__(self, session)

		self["actions"] = ActionMap(["gActions"],
		{
			"exit": self.KeyExit,
			"ok": self.KeyExit
		}, -1)
		
		self["BGlabel"] = Label()
		self["point"] = Pixmap()
		self["pic"] = Pixmap()
		self["file"] = Label()
		
		self.__ConsoleRunning = False
		self.Console = None
		self.__file = file
		self.__cleartmp=cleartmp
		self.__setfilename = setfilename
	
		if file=="grabVideo":
			self.__ConsoleRunning=True
			from Components.Console import Console
			self.Console=Console()
			self.Console.ePopen("grab -v -j 100 " + TMPPICTURE, self.__FinishedConsole)

		self.picload = ePicLoad()
		self.picload_conn = self.picload.PictureData.connect(self.__finish_decode)
		self.onLayoutFinish.append(self.__setPicloadConf)
		
	def KeyExit(self):
		if self.Console:
			if self.__ConsoleRunning!=False:
				self.Console.killAll()
		if self.__cleartmp:
			pathRemove(TMPPICTURE)

		del self.picload
		self.close()
		
	def __FinishedConsole(self, result, retval, extra_args = None):
		self.__ConsoleRunning=False
		if pathExists(TMPPICTURE):
			self.picload.startDecode(TMPPICTURE)

	def __setPicloadConf(self):
		self["BGlabel"].instance.setBackgroundColor(self.__bgcolor)
		self["BGlabel"].instance.invalidate()
		self["file"].instance.setBackgroundColor(self.__bgcolor)
		self["file"].instance.setForegroundColor(self.__fgcolor)
		self["file"].setText(_("please wait, loading ..."))
		self["point"].instance.setPixmap(gLoadPixmap("ico_mp_wait.png"))

		sc = getAspectforPic()
		self._aspectRatio = eSize(sc[0], sc[1])
		self._scaleSize = eSize(self.__maxwidth, self.__maxheight)
		self.picload.setPara([self.__maxwidth, self.__maxheight, sc[0], sc[1], 0, self.__resizetype, "#00000000"])

		if self.Console==None:
			self.picload.startDecode(self.__file)
		
	def __finish_decode(self, picInfo=""):
		self["point"].hide()
		if self.Console:
			self["file"].setText(TMPPICTURE)
		else:
			if self.__setfilename:
				self["file"].setText(self.__setfilename)
			else:
				filename = os_path.join(self.__file)
				self["file"].setText(os_path.basename(filename))

		ptr = self.picload.getData()
		if ptr != None:
			setFullPixmap(self["pic"], ptr, self._scaleSize, self._aspectRatio)

#--------------------------------------------------------------------------------------------

class PicPlayerSummary(Screen):
	def __init__(self, session, parent):
		Screen.__init__(self, session, parent = parent)
		self.skinName = ["PicPlayerSummary"]

#--------------------------------------------------------------------------------------------

class gPicPlayer(Screen,HelpableScreen):
	TMPFILE="/tmp/.tmppic"
	def __init__(self, session, filelist, index, autoplay=False):
		size_w = getDesktop(0).size().width()
		size_h = getDesktop(0).size().height()
		self.__readConfig()
		
		self.__resizetype=2#fast accel
		self.__maxwidth=size_w-(self.__space*2)
		self.__maxheight=size_h-(self.__space*2)
		if self.__maxwidth > 1750:
			self.__resizetype=1#color resize

		self.skin = "<screen position=\"0,0\" size=\"" + str(size_w) + "," + str(size_h) + "\" flags=\"wfNoBorder\" > \
			<widget name=\"BGlabel\" position=\"0,0\" zPosition=\"0\" size=\""+ str(size_w) + "," + str(size_h) + "\" /> \
			<widget name=\"pic\" position=\"" + str(self.__space) + "," + str(self.__space) + "\" size=\"" + str(self.__maxwidth) + "," + str(self.__maxheight) + "\" zPosition=\"1\" /> \
			<widget name=\"point\" position=\""+ str(self.__space+5) + "," + str(self.__space+2) + "\" size=\"20,20\" zPosition=\"2\" alphatest=\"blend\" /> \
			<widget name=\"play_icon\" position=\""+ str(self.__space+25) + "," + str(self.__space+2) + "\" size=\"20,20\" zPosition=\"2\" pixmaps=\"Gemini_default/ico_mp_forward.png,Gemini_default/ico_mp_rewind.png\"  alphatest=\"blend\" /> \
			<widget name=\"label\" position=\""+ str(self.__space+45) + "," + str(self.__space) + "\" size=\""+ str(size_w-(self.__space*2)-50) + ",25\" font=\"Regular;18\" halign=\"left\" zPosition=\"2\" noWrap=\"1\" transparent=\"1\" /></screen>"

		Screen.__init__(self, session)
		HelpableScreen.__init__(self)

		self["actions"] = ActionMap(["gActions"],
		{
			"menu": self.KeyMenu,
			"info": self.KeyInfo,

			"green": self.PlayPause,
			"yellow": self.PlayPause,
			"playpause": self.PlayPause,

			"blue": self.nextPic,
			"next": self.nextPic,
			"right": self.nextPic,

			"red": self.prevPic,
			"prev": self.prevPic,
			"left": self.prevPic,

			"exit": self.KeyExit
		}, -1)
		
		self["BGlabel"] = Label()
		self["point"] = Pixmap()
		self["pic"] = Pixmap()
		self["play_icon"] = MultiPixmap()
		self["label"] = Label()
		self["lcdinfo"] = StaticText()
		self["title"] = StaticText()

		self.index=index
		self.lastindex=index
		self.maxentry=len(filelist)-1
		self.filelist = filelist
		self.shownow = True
		self.direction = 1
		self.picVisible = False
		self.picInfo=""
		self.__rotated=None

		self.__ePicViewer = ePicViewer()
		self.__ePicViewer.callback = self.__finish_rotate

		self.picload = ePicLoad()
		self.picload_conn = self.picload.PictureData.connect(self.__finish_decode)

		self.slideTimer = eTimer()
		self.slideTimer_conn = self.slideTimer.timeout.connect(self.__slidePic)
		if autoplay:
			self.slideTimer.start(self.__slidetimer*1000)

		self.onLayoutFinish.append(self.__LayoutFinish)
	
	def createSummary(self):
		return PicPlayerSummary

	def KeyExit(self):
		if self.__rotated is not None:
			self.session.openWithCallback(self.__exitScreen, MessageBox, _("Save rotated image?"), MessageBox.TYPE_YESNO, default=False)
		else:
			self.__exitScreen()
			
	def __exitScreen(self,ret=False):
		if ret:
			self.__saveRotatedPicture(self.__rotated)
		self.slideTimer.stop()
		del self.slideTimer
		del self.picload
		del self.__ePicViewer
		pathRemove(self.TMPFILE)
		self.close(self.filelist[self.lastindex][1])

	def __LayoutFinish(self):
		self["point"].instance.setPixmap(gLoadPixmap("ico_mp_wait.png"))
		self["BGlabel"].instance.setBackgroundColor(self.__bgcolor)
		
		self.helpList.append((self["actions"], "gActions", [("menu", _("Menu"))]))
		self.helpList.append((self["actions"], "gActions", [("info", _("Information"))]))

		self.helpList.append((self["actions"], "gActions", [("green", _("Pause / Resume") + " " + _("Slideshow"))]))
		self.helpList.append((self["actions"], "gActions", [("yellow", _("Pause / Resume") + " " + _("Slideshow"))]))
		self.helpList.append((self["actions"], "gActions", [("playpause", _("Pause / Resume") + " " + _("Slideshow"))]))

		self.helpList.append((self["actions"], "gActions", [("blue", _("next picture"))]))
		self.helpList.append((self["actions"], "gActions", [("next", _("next picture"))]))
		self.helpList.append((self["actions"], "gActions", [("right", _("next picture"))]))

		self.helpList.append((self["actions"], "gActions", [("red", _("prev picture"))]))
		self.helpList.append((self["actions"], "gActions", [("prev", _("prev picture"))]))
		self.helpList.append((self["actions"], "gActions", [("left", _("prev picture"))]))

		sc = getAspectforPic()
		self._aspectRatio = eSize(sc[0], sc[1])
		self._scaleSize = eSize(self.__maxwidth, self.__maxheight)
		self.picload.setPara([self.__maxwidth, self.__maxheight, sc[0], sc[1], 0, self.__resizetype, "#00000000"])

		if self.slideTimer.isActive()==False:
			self["play_icon"].hide()
		if self.__showInfoLine:
			self["label"].instance.setForegroundColor(self.__fgcolor)
			self["label"].setText("(%d/%d) %s" %(self.index+1,self.maxentry+1,self.filelist[self.index][0]))
		self.__start_decode()
	
	def __start_decode(self):
		self.pic_ready = False
		self.picInfo = self.filelist[self.index][0]
		if self.__canrotate>0:
			self.__ePicViewer.startRotate(self.filelist[self.index][1], self.TMPFILE,self.__maxwidth,self.__maxheight,ROTATE_EXIF)
		else:
			self.__finish_rotate(1,self.filelist[self.index][1])
		if self.__showInfoLine:
			self["point"].show()
			
	def __finish_rotate(self,val,file):
		self.__removeTmp=False
		if val >= 0:
			self.picload.startDecode(file)
			if val == 1 and file==self.TMPFILE and self.__rotated==None:
				self.__removeTmp=True
		
	def __finish_decode(self, picInfo=""):
		self["point"].hide()
		self.pic_ready = True
		self.ShowPicture()
		if self.__removeTmp:
			pathRemove(self.TMPFILE)

	def ShowPicture(self):
		if self.shownow and self.pic_ready:
			if self.picVisible:
				self.picVisible = False
				empty = gPixmapPtr()
				self["pic"].instance.setPixmap(empty)

			ptr = self.picload.getData()
			if ptr != None:
				if self.__showInfoLine and self.__rotated==None:
					self["label"].instance.setForegroundColor(self.__fgcolor)
					self["label"].instance.setBackgroundColor(self.__bgcolor)
					self["label"].setText("(%d/%d) %s" %(self.index+1,self.maxentry+1,self.picInfo))
					self["title"].setText("(%d/%d)" %(self.index+1,self.maxentry+1))
					self["lcdinfo"].setText(self.picInfo)
				if self.__showInfoLine and self.__rotated is not None:
					self["label"].setText("%s      %s" %(_("done..."),self.__rotated))
				self.shownow = False
				self.lastindex = self.index
				setFullPixmap(self["pic"], ptr, self._scaleSize, self._aspectRatio)
				self.picVisible = True
			else:
				print "picture ready but no picture avail!!!!!!!"

			if self.direction > 0:#wie rum
				self.next()
				if self.slideTimer.isActive() and self.__showInfoLine:
					self["play_icon"].setPixmapNum(0)
			else:
				self.prev()
				if self.slideTimer.isActive() and self.__showInfoLine:
					self["play_icon"].setPixmapNum(1)
			self.__start_decode()
			
	def next(self):
		self.direction = 1
		self.index += 1
		if self.index > self.maxentry:
			self.index = 0

	def prev(self):
		self.direction = -1
		self.index -= 1
		if self.index < 0:
			self.index = self.maxentry
			
	def prevPic(self):
		if self.__rotated is not None:
			self.session.openWithCallback(self.__prevPicNow, MessageBox, _("Save rotated image?"), MessageBox.TYPE_YESNO, default=False)
		else:
			self.__prevPicNow()
		
	def __prevPicNow(self,val=False):
		if val:
			self.__saveRotatedPicture(self.__rotated)
		if self.__rotated is not None:
			pathRemove(self.TMPFILE)
			self.__rotated=None
		self.shownow = True
		if self.direction < 0:
			self.ShowPicture()
		else:
			self.index = self.lastindex
			self.prev()
			self.__start_decode()

	def nextPic(self):
		if self.__rotated is not None:
			self.session.openWithCallback(self.__nextPicNow, MessageBox, _("Save rotated image?"), MessageBox.TYPE_YESNO, default=False)
		else:
			self.__nextPicNow()
		
	def __nextPicNow(self,val=False):
		if val:
			self.__saveRotatedPicture(self.__rotated)
		if self.__rotated is not None:
			pathRemove(self.TMPFILE)
			self.__rotated=None
		self.shownow = True
		if self.direction > 0:
			self.ShowPicture()
		else:
			self.index = self.lastindex
			self.next()
			self.__start_decode()

	def __slidePic(self):
		#print "slide to next Picture index=" + str(self.lastindex)
		self.shownow = True
		self.ShowPicture()
		
	def PlayPause(self):
		if self.slideTimer.isActive():
			self.slideTimer.stop()
			self["play_icon"].hide()
		else:
			self.slideTimer.start(self.__slidetimer*1000)
			if self.__showInfoLine:
				self["play_icon"].show()
			self.nextPic()
	
	def KeyMenu(self):
		if self.slideTimer.isActive():
			return
		menu=[]
		if self.__ePicViewer.Running()==False and self.slideTimer.isActive()==False:
			menu.append((_("90 degrees clockwise"), "90", self.filelist[self.lastindex][1]))
			menu.append((_("90 degrees counterclockwise"), "270", self.filelist[self.lastindex][1]))
			menu.append((_("rotate 180 degrees"), "180", self.filelist[self.lastindex][1]))
			menu.append(("--", "--"))
		menu.append((_("Setup"), "setup"))
		self.session.openWithCallback(self.__menuCallback, ChoiceBox, title="", list=menu)

	def __menuCallback(self, what=None):
		if what is None:
			return
		if what[1]=="setup":
			self.session.openWithCallback(self.__readConfig, ConfThumbView, 0)
		elif what[1]=="90" or what[1]=="270" or what[1]=="180":
			self.shownow = True
			self.index = self.lastindex
			self.__rotated = what[2]
			self.pic_ready = False
			self["label"].setText("%s      %s" %(_("Please wait..."),what[0]))
			if self.__rotated is not None and pathExists(self.TMPFILE):
				file = self.TMPFILE
			else:
				file = self.__rotated
			if what[1]=="90":
				self.__ePicViewer.startRotate(file, self.TMPFILE,0,0,ROTATE_90)
			elif what[1]=="270":
				self.__ePicViewer.startRotate(file, self.TMPFILE,0,0,ROTATE_270)
			elif what[1]=="180":
				self.__ePicViewer.startRotate(file, self.TMPFILE,0,0,ROTATE_180)

	
	def __saveRotatedPicture(self,file):
		if pathExists(self.TMPFILE):
			from Tools.Directories import copyfile
			if copyfile(self.TMPFILE, file)!=0:
				self.session.open(MessageBox, _("Error executing the command"), MessageBox.TYPE_ERROR, timeout=5)

	def __callback_thumb(self,index):
		if index != self.lastindex:
			self.index = index
			self.shownow = True
			self["label"].setText(_("Please wait..."))
			self.__start_decode()
		
	def KeyInfo(self):
		if self.slideTimer.isActive():
			return
		mfile = libgeminimain.getPyList(GETFILEINFOS,self.filelist[self.lastindex][1])
		if mfile and self.__ePicViewer.Running()==False:
			from searchMediaInfo import BrowserSmallFileInfos
			self.session.open(BrowserSmallFileInfos, mfile, self.__ePicViewer.getExif(self.filelist[self.lastindex][1]))
			
	def __readConfig(self,val=False):
		self.__space = cgevent.getConfig("gpicplayer_space",40)
		self.__showInfoLine = cgevent.getConfig("gpicplayer_infoline",1)
		self.__slidetimer = cgevent.getConfig("gpicplayer_slidetime",10)
		self.__canrotate = cgevent.getConfig("gpicplayer_canrotate",1)
		
		self.__bgcolor,self.__fgcolor = getBrowserColor()

		if val:
			self["BGlabel"].instance.setBackgroundColor(self.__bgcolor)
			self["label"].instance.setForegroundColor(self.__fgcolor)
			self["label"].instance.setBackgroundColor(self.__bgcolor)

#------------------------------------------------------------------------------------

class gPicPlayerThumb(CThumbView):
	def __init__(self, session, name=None, setPath=None, autostart=False):
		if setPath==None:
			startdir = cgevent.getConfig("gpicplayer_StartDir"," ")
			if startdir == " ":
				setPath=cgevent.getConfig("gpicplayer_lastpath","/media/")
			else:
				setPath=startdir + "/.."
		CThumbView.__init__(self, session, _("Picture-Browser"), 0, setPath, autostart)
		self["actions"] = ActionMap(["gActions"],
		{
			"exit": self.KeyExit
		}, -1)
		
	def KeyExit(self):
		CThumbView.Exit(self,"gpicplayer_lastpath")
		#cleanexit(__name__)
		
class gMoviePlayerThumb(CThumbView):
	def __init__(self, session, name=None, setPath=None, autostart=False):
		if setPath==None:
			startdir = cgevent.getConfig("gmovieplayer_StartDir"," ")
			if startdir == " ":
				setPath=cgevent.getConfig("gmovieplayer_lastpath","/media/")
			else:
				setPath=startdir + "/.."
		CThumbView.__init__(self, session, _("Video-Browser"), 1, setPath, autostart)
		self["actions"] = ActionMap(["gActions"],
		{
			"exit": self.KeyExit
		}, -1)
		
	def KeyExit(self):
		CThumbView.Exit(self,"gmovieplayer_lastpath")
		#cleanexit(__name__)
		

class gMusicPlayerThumb(CThumbView):
	def __init__(self, session, name=None, setPath=None, autostart=False):
		if setPath==None:
			startdir = cgevent.getConfig("gmusicplayer_StartDir"," ")
			if startdir == " ":
				setPath=cgevent.getConfig("gmusicplayer_lastpath","/media/")
			else:
				setPath=startdir + "/.."
		CThumbView.__init__(self, session, _("Music-Browser"), 2, setPath, autostart)
		self["actions"] = ActionMap(["gActions"],
		{
			"exit": self.KeyExit
		}, -1)
		
	def KeyExit(self):
		CThumbView.Exit(self,"gmusicplayer_lastpath")
		#cleanexit(__name__)
