# -*- coding: utf-8 -*-
from Plugins.Bp.geminimain.gLocale import _
from Plugins.Bp.geminimain.downloadScreen import RawDownload
from Plugins.Bp.geminimain.MenuXMLlist import MenuXMLlist
from Plugins.Bp.geminimain.WidgetTools import setFullPixmap
from Plugins.Bp.geminimain.WidgetVariableList import WidgetVariableList
from Plugins.Bp.geminimain.gTools import getXMLFile, XML_RSS_LIST, pathExists, gPluginPath, getEntryString, getAspectforPic, cleanexit, pathRemove

from Components.ActionMap import ActionMap
from Screens.Screen import Screen
from Components.Label import Label
from Components.MenuList import MenuList
from Components.Pixmap import Pixmap
from Components.ScrollLabel import ScrollLabel
from Components.Sources.StaticText import StaticText
from enigma import ePicLoad, eTimer, eSize

from skin import loadSkin
loadSkin(gPluginPath + "geminirssreader/skin.xml")

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

class RssReader(MenuXMLlist, WidgetVariableList):
	path = gPluginPath + "geminirssreader/gemini_rss.xml"
	userPath = "/etc/enigma2/gemini_rss.xml"
	if pathExists(userPath):
		path = userPath
	else:
		from Tools.Directories import copyfile
		copyfile(path, userPath)
	
	def __init__(self, session, title=None):
		WidgetVariableList.__init__ (self, session, _("Rss Reader"), icon="geminirssreader/icon_rssreader.png", ListIcon=(30,25), showMenuPix=True)
		MenuXMLlist.__init__(self, self.path, _("Rss Reader"), "geminirssreader/rss_atom.png", sort=False)
		self.skinName = [self.__class__.__name__,"VariableListNoButton_" + self.__class__.__name__,"VariableListNoButton"]
		
		self.__clock_timer = eTimer()
		self.__clock_timer_conn = self.__clock_timer.timeout.connect(self.__startDownloadXML)

	def KeyOk(self):
        	val = self.pressOK()
		if isinstance(val, str):
			self.SetTitle(val)
		elif isinstance(val, tuple):
			self.SetLabel(_("Downloading data, please wait..."))
			self.__clock_timer.start(300,True)
			
	def __startDownloadXML(self):
		val = self.pressOK()
		header = None
		if val[3] != "":
			header = {"Cookie": val[3],"Accept": "text/plain"}
		htmldata = RawDownload.startDL(val[1], session=self.session, header=header)
		if htmldata:
			rlist = getXMLFile(self, XML_RSS_LIST, htmldata, True)
			if len(rlist)>0:
				self.session.open(RssLister, rlist)
		self.SetLabel()

	def KeyExit(self, val=None):
		del self.__clock_timer
		self.close(val)
		cleanexit(__name__)

#--------------------------------------------------------------------------------------------------------
#inhalt
TITLE = 0
DESCR = 1
LINK = 2
TIME = 3
CONTENT = 4
PICTURE = 5

#Content
C_TITLE = 0
C_ENTRY = 1
C_GOUP = 2

class RssLister(Screen):
	TEMP_FILE="/tmp/.picrss"
	def __init__(self, session, rsslisten):
		Screen.__init__(self, session)
		self.skinName = [self.__class__.__name__]
		self["actions"] = ActionMap(["gActions"],
		{
			"ok": self.KeyOk,
			"exit": self.KeyExit,
		}, -1)

		self["menu"] = MenuList([])
		self["label0"] = Label()
		self["label1"] = Label()
		self["label2"] = Label()
		self["desc"] = Label()
		self["pic"] = Pixmap()

		self.__rsslisten = rsslisten
		self.__downloadPic=None
		
		self.picload = ePicLoad()
		self.picload_conn = self.picload.PictureData.connect(self.showPic)
		
		self.onLayoutFinish.append(self.firstStart)
		self["menu"].onSelectionChanged.append(self.selectionChanged)
		
		self.__clock_timer = eTimer()
		self.__clock_timer_conn = self.__clock_timer.timeout.connect(self.__startDownloadPic)

	def KeyExit(self):
		pathRemove(self.TEMP_FILE)
		self.close()

	def firstStart(self):
		sc=getAspectforPic()
		self._aspectRatio = eSize(sc[0], sc[1])
		self._scaleSize = eSize(self["pic"].instance.size().width(), self["pic"].instance.size().height())
		self.picload.setPara([self["pic"].instance.size().width(), self["pic"].instance.size().height(), sc[0], sc[1], 0, 1, "#00000000"])

		tmplist = []
		for x in self.__rsslisten:
			if x[CONTENT] == C_TITLE:
				self["label0"].setText(x[TITLE] + getEntryString(len(self.__rsslisten)-1))
				self["label1"].setText(x[DESCR])
				if x[TIME] != "":
					self["label2"].setText(x[TIME])
				else:
					self["label2"].setText(x[LINK])
				if x[PICTURE]!="" and x[PICTURE][0]!="/" and self.__downloadPic==None: #Bild laden
					self.__downloadPic=x[PICTURE]
			else:
				tmplist.append((x[TITLE], x))
		self["menu"].l.setList(tmplist)
		if self.__downloadPic:
			self.__clock_timer.start(300,True)

	def selectionChanged(self):
		sel = self["menu"].getCurrent()
		tmpstr = ""
		if sel and sel[1]:
			val = sel[1]
			if val[TIME] != "":
				tmpstr += val[TIME] + "\n"
			if val[DESCR] != "":
				tmpstr += val[DESCR]
			elif val[TITLE] != "":
				tmpstr += val[TITLE]
				
		self["desc"].setText(tmpstr)

	def KeyOk(self):
		if self["menu"].getCurrent():
			self.session.openWithCallback(self.moveIndex, RssView, self.__rsslisten, self["menu"].getSelectionIndex())
	
	def moveIndex(self, val = 0):
		self["menu"].moveToIndex(val)
		
	def __startDownloadPic(self):
		data = RawDownload.startDL(self.__downloadPic)
		if data:
			try:
				newfile=open(self.TEMP_FILE,'wb')
				if newfile:
					newfile.write(data)
					newfile.close()
					if pathExists(self.TEMP_FILE):
						self.picload.startDecode(self.TEMP_FILE)
			except Exception, e:
				print "[%s] <%s>"%(__name__,e)

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

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

class RssView(Screen):
	def __init__(self, session, tmplist = [], index = 0):
		Screen.__init__(self, session)
		self.skinName = [self.__class__.__name__]
		self["text"] = ScrollLabel()
		self["blue"] = Label()
		self["blue2"] = Label()

		self["actions"] = ActionMap(["gActions"],
		{
			"ok": self.KeyExit,
			"exit": self.KeyExit,
			"up": self["text"].pageUp,
			"down": self["text"].pageDown,
			"left": self.KeyLeft,
			"right": self.KeyRight
		}, -1)
		
		self.rsslist = []
		newtitle = ""
		self["title"] = StaticText()
		
		for x in tmplist:
			if x[CONTENT] == C_ENTRY:
				self.rsslist.append(x)
			else:
				newtitle = x[TITLE]
				
		self["Title"].text = newtitle
		self["title"].text = newtitle
		self.maxPos = len(self.rsslist)-1
		self.index = index
		self.set_text()
		
	def KeyRight(self):
		self.index += 1
		if self.index > self.maxPos:
			self.index = 0
		self.set_text()
		
	def KeyLeft(self):
		self.index -= 1
		if self.index < 0:
			self.index = self.maxPos
		self.set_text()
			
	def set_text(self):
		self["text"].setText(self.rsslist[self.index][DESCR] or self.rsslist[self.index][TITLE] or _("No info available"))
		self["blue"].setText(_("side") + " " + str(self.index + 1) + " / " + str(self.maxPos + 1))
		self["blue2"].setText(self.rsslist[self.index][TITLE])
		
	def KeyExit(self):
		self.close(self.index)
