# -*- coding: utf-8 -*-
from gLocale import _
from enigma import ePoint, quitMainloop
from gTools import libgeminimain, cleanexit, pathExists, pathRemove, getInstalledLang, gLoadPixmap, checkCacheDirs, getColorPic, VDesktopfound, GeminiCacheDirs, DEFAULTGEMINICACHEDIR
from plugin import cgevent
from GeminiDef import *

from WidgetVariableList import WidgetVariableList
from WidgetConfig import gConfigWindow, gConfigOnOff, gConfigSelection, CONFIGSEPERATOR, gConfigDirectory
from Components.config import config, NoSave, getConfigListEntry, ConfigText, ConfigInteger

from enigma import eEPGCache
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Components.Console import Console
from Components.ActionMap import ActionMap
from Components.Label import Label


class confGeneral(gConfigWindow ):
	EXTRAPLUGINFILE = "/etc/apt/sources.list.d/gemini33-extraPlugins-feed.list"
	
	def __init__(self, session, name=None):
		
		self.Console = Console()

		geminiconf = libgeminimain.getGeminiConf()
		self.__selected=0
		self.__OKstate = cgevent.getConfig("OkButton",0)
		self.__DisplayAsClock = cgevent.getConfig("DisplayAsClock",0)

		menu = [(0, _("off")),(1, _("blinking")), (2, _("on"))]
		config.bp.bgevent = NoSave(gConfigSelection(default=cgevent.getConfig("bg_event",1), choices=menu))
		config.bp.orbital = NoSave(gConfigOnOff(default=bool(geminiconf & ORBITAL_POS_SHOW)))
		config.bp.channelnr = NoSave(gConfigOnOff(default=bool(geminiconf & CHANNEL_NR_SHOW)))
		config.bp.position = NoSave(gConfigSelection(choices=[_("View") + "/" + _("Choose")]))
		config.bp.piconpool = NoSave(gConfigDirectory(default=cgevent.getConfig("location_picon_pool","/usr/share/enigma2/piconpool"), visible_width=35))
		config.bp.picon = NoSave(gConfigDirectory(default=cgevent.getConfig("location_picon","/usr/share/enigma2/picon"), visible_width=35))
		config.bp.piconoled = NoSave(gConfigDirectory(default=cgevent.getConfig("location_picon_oled","/usr/share/enigma2/picon_oled"), visible_width=35))
		config.bp.piconmini = NoSave(gConfigDirectory(default=cgevent.getConfig("location_picon_mini","/usr/share/enigma2/picon_50x30"), visible_width=35))
		menu = [(0, _("off")),(1, _("Show '%s' in the infobar") %"UP"), (2, _("Show Icon")), (3, _("Show Message"))]
		config.bp.search = NoSave(gConfigSelection(default=cgevent.getConfig("checkUpgrade",0), choices=menu))
		config.bp.extra = NoSave(gConfigOnOff(default=int(pathExists(self.EXTRAPLUGINFILE))))
		config.bp.cache = NoSave(gConfigDirectory(default=cgevent.getConfig("geminicache",DEFAULTGEMINICACHEDIR[:-1]), visible_width=35))
		config.bp.epgcache = NoSave(gConfigDirectory(default=cgevent.getConfig("epgcachedir","/etc/enigma2"), visible_width=35))
		menu = [(0, _("Function disable")),(1, _("Function enable (off)")), (2, _("Function enable (on)"))]
		config.bp.okbutton = NoSave(gConfigSelection(default=self.__OKstate, choices=menu))
		config.bp.mediascan = NoSave(gConfigOnOff(default=cgevent.getConfig("media_scan",1)))
		config.bp.display = NoSave(gConfigOnOff(default=self.__DisplayAsClock))
		
		#ChannelSelection
		self.__chsmenu=[]
		count=0
		defaultheight = cgevent.getConfig("ChannelSelHeight",-1)
		
		for x in cgevent.ChannelSelectionList:
			if int(x[0]) == cgevent.ChannelSelectionHeight:
				self.__chsmenu.append((count,"%s (%s)" %(x[0],_("Default"))))
				if defaultheight==-1:
					defaultheight=count
			else:
				self.__chsmenu.append((count,x[0]))
			count += 1
		if len(self.__chsmenu):
			config.bp.channelselection = NoSave(gConfigSelection(default=defaultheight, choices=self.__chsmenu))

		list = []
		list.append(getConfigListEntry(_("Location for %s") %"Picon-Pool", config.bp.piconpool))
		list.append(getConfigListEntry(_("Location for %s") %"Picons", config.bp.picon))
		list.append(getConfigListEntry(_("Location for %s") %"Mini-Picons", config.bp.piconmini))
		list.append(getConfigListEntry(_("Location for %s") %"OLED-Picons", config.bp.piconoled))
		list.append(getConfigListEntry(_("Location for %s") %"Gemini-Cache", config.bp.cache))
		list.append(getConfigListEntry(_("Location for %s") %"EPG-Cache", config.bp.epgcache))
		list.append(CONFIGSEPERATOR())
		list.append(getConfigListEntry(_("Automatically scan for Media-Infos?"), config.bp.mediascan))
		list.append(CONFIGSEPERATOR())
		list.append(getConfigListEntry(_("Display always as clock"), config.bp.display))
		list.append(getConfigListEntry(_("OK Button for show Infobar"), config.bp.okbutton))
		list.append(getConfigListEntry(_("Show background events ?"), config.bp.bgevent))
		list.append(getConfigListEntry(_("Show Orbitalposition") + " " + _("(only Gemini-Skins)"), config.bp.orbital))
		list.append(getConfigListEntry(_("Show Channelnumber") + " " + _("(only Gemini-Skins)"), config.bp.channelnr))
		list.append(getConfigListEntry(_("Position of the Infobar"), config.bp.position))
		if len(self.__chsmenu):
			list.append(getConfigListEntry(_("Height of entries in the channel list"), config.bp.channelselection))
		list.append(CONFIGSEPERATOR())
		list.append(getConfigListEntry(_("Looking for daily updates"), config.bp.search))
		list.append(getConfigListEntry(_("use DREAM") + " " +  _("Storage devices") + _(" ?"), config.plugins.bp.devicemanager))

		if VDesktopfound:
			config.bp.vdesktop = NoSave(gConfigOnOff(default=cgevent.getConfig("vdesktop_conf",1)))
			list.append(CONFIGSEPERATOR())
			list.append(getConfigListEntry(_("Virtual Desktop"), config.bp.vdesktop))

		gConfigWindow.__init__ (self, session, name or _("General"), list=list, icon="icon_general.png")

	def SelectionChangedNow(self):
		gConfigWindow.SelectionChangedNow(self)
		self.setRB()
		self.__selected=0
		if self.getCurrendValue() == config.bp.cache:
			self.setRB(_("Delete"))
			self.__selected=1
		
	def KeyLeft(self):
		if self.getCurrendValue() == config.bp.position:
			self.session.open(InfobarPreview, False)
		else:
			gConfigWindow.KeyLeft(self)

	def KeyRight(self):
		if self.getCurrendValue() == config.bp.position:
			self.session.open(InfobarPreview, True)
		else:
			gConfigWindow.KeyRight(self)

	def KeyGreen(self):
		config.plugins.bp.devicemanager.save()
		cgevent.setConfig("media_scan", config.bp.mediascan.value)
		cgevent.setConfig("DisplayAsClock", config.bp.display.value)
		#ChannelSelection
		if len(self.__chsmenu):
			cgevent.setConfig("ChannelSelHeight",config.bp.channelselection.value)
			cgevent.setChannelSelection(config.bp.channelselection.value)
		#vdesktop
		if VDesktopfound:
			cgevent.setConfig("vdesktop_conf",config.bp.vdesktop.value)
		
		libgeminimain.gFunktion(SETGENERAL, (config.bp.bgevent.value, config.bp.picon.value, config.bp.piconoled.value, config.bp.piconmini.value, config.bp.piconpool.value, config.bp.search.value, config.bp.orbital.value, config.bp.channelnr.value, config.bp.cache.value))
		
		#Cache
		checkCacheDirs()

		#EPG
		epgcachefile = config.bp.epgcache.value + "/epg.db"
		cgevent.setConfig("epgcachedir", config.bp.epgcache.value)
		config.misc.epgcache_filename = ConfigText(default = epgcachefile)
		eEPGCache.getInstance().setCacheFile(epgcachefile)
		#OK Button
		cgevent.setConfig("OkButton", config.bp.okbutton.value)
		cgevent.setOkButtonConfig()
		
		#muss restart
		restart = False
		if self.__OKstate == 0 and config.bp.okbutton.value != 0:
			restart = True
		if self.__OKstate > 0 and config.bp.okbutton.value == 0:
			restart = True
		if self.__DisplayAsClock != config.bp.display.value:
			restart = True
	
		if restart:
			self.session.openWithCallback(self.__restartOK, MessageBox, _("Do you want to restart Enigma2?"), MessageBox.TYPE_YESNO)
		else:
			self.KeyExit()
	
	def __restartOK(self, result):
		if result:
			quitMainloop(3)
		else:
			self.KeyExit()

	def KeyRed(self):
		if self.__selected==1:
			cmd=""
			for x in GeminiCacheDirs:
				if cmd!="":
					cmd += " & "
				cmd += "rm -r '%s/%s/'*" %(config.bp.cache.value,x)
			self.Console.ePopen(cmd, self.__FinishedConsole)
			
	def __FinishedConsole(self, result, retval, extra_args = None):
		checkCacheDirs()
		self.session.open(MessageBox, _("done..."), MessageBox.TYPE_INFO, timeout=3)

	def KeyExit(self):
		self.close()
		cleanexit(__name__)

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

class InfobarPreview(Screen):
	def __init__(self, session, activ=False):
		self.activ = activ
		self.size = cgevent.INFOBAR_SIZE
		self.pos = cgevent.INFOBAR_POSITION
		self.offset_x = cgevent.getConfig("infobar_offset_x",0)
		self.offset_y = cgevent.getConfig("infobar_offset_y",0)

		self.skin = "<screen position=\"" + str(self.pos.x()+self.offset_x) + "," + str(self.pos.y()+self.offset_y) + "\" size=\"" + str(self.size.width()) + "," + str(self.size.height()) + "\" flags=\"wfNoBorder\" > \
				<widget name=\"label\" position=\"5,5\" size=\"" + str(self.size.width()-10) + "," + str(self.size.height()-10) + "\" font=\"Regular;19\" halign=\"center\" valign=\"center\" /> </screen>"

		Screen.__init__(self, session)

		self["actions"] = ActionMap(["gActions"],
		{
			"ok": self.KeyOK,
			"up": self.KeyUp,
			"down": self.KeyDown,
			"left": self.KeyLeft,
			"right": self.KeyRight,
			"exit": self.KeyExit
		}, -1)

		self["label"] = Label(_("Position") + " = " + str(self.pos.x() + self.offset_x) + "," + str(self.pos.y() + self.offset_y))
		self.onLayoutFinish.append(self.__InfobarMove)

	def __InfobarMove(self):
		if self.activ:
			self.instance.move(ePoint(self.pos.x() + self.offset_x, self.pos.y() + self.offset_y))

			self["label"].setText(_("Press (left, right) or (up, down)\n") + _("Press OK to save settings") + "\n" + _("Original Position") + " = " + str(self.pos.x()) + "," + str(self.pos.y()) + "\n" + _("New Position") + " = " + str(self.pos.x() + self.offset_x) + "," + str(self.pos.y() + self.offset_y))

	def KeyUp(self):
		self.offset_y -= 1
		self.__InfobarMove()
		
	def KeyDown(self):
		self.offset_y += 1
		self.__InfobarMove()
		
	def KeyRight(self):
		self.offset_x += 1
		self.__InfobarMove()

	def KeyLeft(self):
		self.offset_x -= 1
		self.__InfobarMove()
		
	def KeyOK(self):
		if self.activ:
			cgevent.setConfig("infobar_offset_x", self.offset_x)
			cgevent.setConfig("infobar_offset_y", self.offset_y)
			cgevent.setInfobarOffset()
		self.KeyExit()
		
	def KeyExit(self):
		self.close()

