# -*- coding: utf-8 -*-

from gLocale import _
from GeminiDef import *
from gTools import libgeminimain, cleanexit, BoxType, gLoadPixmap, getEntryString, gPluginPath, pathExists, ctoolsclass, DEFAULTGEMINICACHEDIR, myExecute
from WidgetVariableList import WidgetVariableList
from WidgetMessageBox import gMessageBox
from ShowFileList import ShowFileList
from plugin import cgevent, geventNotifier

from enigma import eConsoleAppContainer, iServiceInformation
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox

#----------------------------------------------------------------------
from Screens.ServiceInfo import ServiceInfo, ServiceInfoListEntry, TYPE_SERVICE_INFO, TYPE_TEXT, TYPE_VALUE_DEC

class gServiceInfo(ServiceInfo):
	def __init__(self, session, name=None):
		ServiceInfo.__init__ (self, session)
		self.skinName = ["ServiceInfo"]
	
	def fillList(self, Labels):
		tlist = [ ]

		for item in Labels:
			if item[1] is None:
				continue;
			value = item[1]
			if len(item) < 4:
				tlist.append(ServiceInfoListEntry(item[0]+":", value, item[2]))
			else:
				tlist.append(ServiceInfoListEntry(item[0]+":", value, item[2], item[3]))
		
		if self.type == TYPE_SERVICE_INFO:
			tlist.append(ServiceInfoListEntry("", "",TYPE_TEXT))
			if Labels and len(Labels)>=1:
				if Labels[0][0]==_("Name"):
					caidlist = libgeminimain.getPyList(GETCAIDLIST)
					if len(caidlist):
						tlist.append(ServiceInfoListEntry(_("Coding Systems:"), len(caidlist),TYPE_VALUE_DEC))
						for x in caidlist:
							tstr = caid = "0x%04X" % (x[0])
							if x[1] == 1:
								tstr += " (" + _("used") + ")"
							tlist.append(ServiceInfoListEntry(tstr , x[2], TYPE_TEXT))
				elif Labels[0][0]==_("Video PID"):
					caidlist = libgeminimain.getPyList(GETCAIDLIST)
					if len(caidlist):
						for x in caidlist:
							if x[3]>0:
								tstr = "0x%04x (%dd)    ID: 0x%06x" % (x[4], x[4], x[3])
							else:
								tstr = "0x%04x (%dd)" % (x[4], x[4])
							if x[1] == 1:
								tstr += "*"
							tlist.append(ServiceInfoListEntry(x[2] + ":", tstr, TYPE_TEXT))

		self["infolist"].l.setList(tlist)
#----------------------------------------------------------------------

class AboutScreen(WidgetVariableList):
	GEMINIMAIN=0
	GEMINIPLUGIN=1
	TPMSIG=2
	GETSSL=3
	GETDVB=4
	GETCACHE=5
	def __init__(self, session, name=None):
		WidgetVariableList.__init__ (self, session, title = name or _("About") , icon="icon_glogo.png", NameRed=_("Changelog"))
		self.skinName = [self.__class__.__name__,"VList3Button2Entry_" + self.__class__.__name__,"VList3Button2Entry"]
		self.cachesize = self.dvbmodules = self.ssl = None
		self.onLayoutFinish.append(self.__fillListe)

		from Components.About import about
		self.__ImageVersion = about.getImageVersionString()
		self.__EnigmaVersion =  about.getEnigmaVersionString()

	def __fillListe(self):
		index=self.GetIndex()
		from os import path as os_path, listdir as os_listdir
		from gVersion import gVersion as tVersion
		from Tools.DreamboxHardware import getFPVersion
		BoxSignatur = ctoolsclass.getBoxSignatur()
		SkinInfos = ctoolsclass.getSkinInfos()

		list=[]
		list.append((_("Gemini-Version:"),None, tVersion,None,self.GEMINIMAIN))
		list.append((_("Dreambox:"),None, BoxType,None))
		list.append((_("FP Version:"),None,str(getFPVersion() or _("not found")),None))
		list.append((_("Enigma") + " " + _("Version") + ":",None,self.__EnigmaVersion or  _("not found"),None))
		list.append((_("Image") + ":",None,self.__ImageVersion or  _("not found"),None))
		if BoxSignatur:
			list.append((_("TPM Signature") + ":",None, _("valid"),None))
		else:
			list.append((_("TPM Signature") + ":",None, _("Press red key for details"),None,self.TPMSIG))

		if self.ssl:
			list.append((_("Secondstage:"),None, self.ssl,None))
		else:
			list.append((_("Secondstage:"),None, _("Press red key for details"),None,self.GETSSL))
		if self.dvbmodules:
			list.append((_("DVB-Modules:"),None, self.dvbmodules,None))
		else:
			list.append((_("DVB-Modules:"),None, _("Press red key for details"),None,self.GETDVB))

		from lib import libgtools
		l = libgtools.AboutInfos()
		del libgtools
		if(len(l))==2:
			list.append((_("Kernel:"),None,l[1],ctoolsclass.getSeperatorPic()))
			list.append((_("Twitter:"),None,"twitter.com/#!/GeminiProject3",None))
			list.append((_("Uptime:"),None,libgeminimain.getHumanDate(4,l[0]),None))
			if self.cachesize:
				list.append((_("Gemini-Cache")+":",None,self.cachesize,ctoolsclass.getSeperatorPic()))
			else:
				list.append((_("Gemini-Cache")+":",None,_("Press red key for details"),ctoolsclass.getSeperatorPic(), self.GETCACHE))

		if SkinInfos[0] != "":
			list.append((_("Skin") + "-" +_("Name")+":",None,SkinInfos[0],None))
			list.append((_("Skin") + "-" +_("Version")+":",None,SkinInfos[1],None))
			list.append((_("Skin") + "-" +_("Package")+":",None,SkinInfos[2],ctoolsclass.getSeperatorPic()))

		try:
			for c in os_listdir(gPluginPath):
				directory_plugin = gPluginPath + c
				if not os_path.isdir(directory_plugin):
					continue
				if c != "geminimain":
					if pathExists(directory_plugin + "/gVersion.py"):
						exec "from Plugins.Bp.%s.gVersion import gVersion" %(c)
						if pathExists(directory_plugin + "/changelog.txt"):
							list.append((c,None, gVersion,None,self.GEMINIPLUGIN))
						else:
							list.append((c,None, gVersion,None))
		except Exception, e:
			print "[%s] <%s>"%(__name__,e)

		self.SetList(list)
		self.SetIndex(index)
		self.hideLabel()
		
	def selectionChanged(self):
		self.SetRB()
		sel = self.getCurrentEntry()
		if sel and len(sel)==5:
			if sel[4]==self.GEMINIMAIN or sel[4]==self.GEMINIPLUGIN:
				self.SetRB(_("Changelog"))
			elif sel[4]==self.TPMSIG or sel[4]==self.GETSSL or sel[4]==self.GETDVB or sel[4]==self.GETCACHE:
				self.SetRB(_("Start"))

	def KeyRed(self):
		sel = self.getCurrentEntry()
		if sel and len(sel)==5:
			if sel[4]==self.GEMINIMAIN:
				self.session.open(ShowFileList, file=gPluginPath+"geminimain/changelog.txt", selectlast=False)
			elif sel[4]==self.GEMINIPLUGIN:
				self.session.open(ShowFileList, file=gPluginPath+sel[0]+"/changelog.txt", selectlast=False)
			elif sel[4]==self.TPMSIG:
				ctoolsclass.getBoxSignatur(True)
				self.__fillListe()
			elif sel[4]==self.GETSSL:
				from WidgetIpkg import ipkVersion
				self.ssl = ipkVersion("dreambox-secondstage")
				self.__fillListe()
			elif sel[4]==self.GETDVB:
				from WidgetIpkg import ipkVersion
				self.dvbmodules = ipkVersion("dreambox-dvb-modules")
				self.__fillListe()
			elif sel[4]==self.GETCACHE:
				dlist = libgeminimain.getDirInfo(DEFAULTGEMINICACHEDIR)
				if dlist and len(dlist) == 3:
					self.cachesize = dlist[0] + "B"
					self.__fillListe()
		
	def KeyExit(self):
		self.close()
		cleanexit(__name__)
#----------------------------------------------------------------------

class MountPoints(WidgetVariableList):
	def __init__(self, session, name=None):
		WidgetVariableList.__init__ (self, session, title = name or _("Mountpoints") , list=list, ListIcon=(66,66), LinesProEntry=4, icon="icon_mount.png", selectionEnabled=0)
		self.skinName = [self.__class__.__name__,"VariableListNoButton_" + self.__class__.__name__,"VariableListNoButton"]
		self.onLayoutFinish.append(self.__fillListe)
		geventNotifier.append((EVENT_MOUNT, self.__fillListe))
	
	def __fillListe(self, what=0, val=""):
		list=[]
		for x in libgeminimain.getPyList(GETMOUNTLIST):
			prozstr = ""
			if x[PART_T_SIZE] > 0:
				proz = x[PART_U_SIZE]*100/x[PART_T_SIZE]
				if proz>0 and proz<100:
					prozstr = " (" + str(proz) + "% " + _("used") + ")"

			tstr = _("Device") + ": " + x[PART_DEVPATH] + prozstr + "\n"
			tstr += _("Mountpoint") + ": " + x[PART_MPOINT] + " (" + x[PART_FS] + ")\n"
			if not bool(x[PART_FS_TYPE] & 2):#nicht bei AutoFS
				tstr += _("Parameters") + ": " + x[PART_OPTIONS] + "\n"
				tstr += "%s: (%s %s %s %s %s %s)" % (_("Size"), _("total"), libgeminimain.getHumanSize(x[PART_T_SIZE]), _("used"), libgeminimain.getHumanSize(x[PART_U_SIZE]), _("free"), libgeminimain.getHumanSize(x[PART_F_SIZE]))
			list.append((tstr, gLoadPixmap(x[PART_PIC])))
		self.SetList(list)
	
	def KeyUp(self):
		WidgetVariableList.KeyLeft(self)
		WidgetVariableList.KeyUp(self)

	def KeyDown(self):
		WidgetVariableList.KeyRight(self)
		WidgetVariableList.KeyDown(self)

	def KeyExit(self):
		geventNotifier.remove((EVENT_MOUNT, self.__fillListe))
		self.close()
		cleanexit(__name__)

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

class ProcessInfo(WidgetVariableList):
	def __init__(self, session, name=None):
		WidgetVariableList.__init__ (self, session, title = name or _("Process"), icon="icon_process.png", NameGreen=_("View details"), NameBlue=_("Menu"), SepLine=True)
		self.skinName = [self.__class__.__name__,"VariableList3Button_" + self.__class__.__name__, "VariableList3Button"]
		
		from lib import libgtools
		self.libgtools = libgtools
		self.onLayoutFinish.append(self.__fillList)
	
	def __fillList(self):
		self.hideLabel()
		list=[]
		list.append(("PID\tCommand\tStatus  Time",ctoolsclass.getSeperatorPic()))
		for x in self.libgtools.ProgressInfo():
			pro_str = str(x[0]) + "\t" + x[1] + "\t" + x[2] + "           " + str(x[3])
			list.append((pro_str, None, x[0], x[1]))
		self.SetList(list)
		self.SetIndex(1)
		
	def KeyBlue(self):
		val = self.getCurrentEntry()
		if val and len(val) == 4:
			menu = []
			menu.append(("SIGHUP", 0))
			menu.append(("SIGINT", 0))
			menu.append(("SIGQUIT", 0))
			menu.append(("SIGTRAP", 0))
			menu.append(("SIGABRT", 0))
			menu.append(("SIGKILL", 0))
			menu.append(("SIGUSR1", 0))
			menu.append(("SIGALRM", 0))
			menu.append(("SIGTERM", 0))
			menu.append(("SIGCONT", 0))
			menu.append(("SIGSTOP", 0))
			self.session.openWithCallback(self.__menuCallback, ChoiceBox, list=menu, title=_("send signal to this process...\n'") + val[3] + "'")

	def __menuCallback(self, val):
		if val != None:
			cmd = "killall -" + val[0] + " " + self.getCurrentEntry()[3]
			myExecute(cmd)
			self.__fillList()
	
	def KeyOk(self):
		self.KeyGreen()
		
	def KeyGreen(self):
		val = self.getCurrentEntry()
		if val and len(val) == 4:
			self.session.open(ShowFileList, cmdlist=["cat /proc/" + str(val[2]) + "/status"])
		
	def KeyExit(self):
		del self.libgtools
		self.close()
		cleanexit(__name__)

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

class KernelInfo(ShowFileList):
	def __init__(self, session, name=None):
		ShowFileList.__init__ (self, session, cmdlist=["dmesg"])
		
#----------------------------------------------------------------------

class LuksInfo(gMessageBox):
	def __init__(self, session, device):
		gMessageBox.__init__ (self, session, title=_("Encryption"), icon="dev_luks.png")
		self.__device = device
		self.onLayoutFinish.append(self.__fillLabel)

	def __fillLabel(self):
		from WidgetTools import luksinfo
		ilist = luksinfo(self.__device)
		if len(ilist)==7:
			text = ilist[1] + "\n"
			text += ilist[2] + "\n"
			text += ilist[4] + "\n"
			text += ilist[5] + "\n"
			text += ilist[6]
			self.setText(text)

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


class SpeedcheckInfo(gMessageBox):
	def __init__(self, session, testfile, testsize):
		gMessageBox.__init__ (self, session, icon="mess_trafficinfo.png", text=_("speed test running, please wait...")+"\n")
		self.__testsize=testsize
		self.__finished=False
		self.container = eConsoleAppContainer()
		self.container_appClosed_conn = self.container.appClosed.connect(self.__finishedC)
		self.container_dataAvail_conn = self.container.dataAvail.connect(self.__dataAvail)
		self.container.execute("/usr/bin/gBackground -f 1 -d '%s' -s %s" %(testfile, testsize))

	def __finishedC(self, retval):
		oldstr = self.getText()
		oldstr += "\n\n" + _("done...")
		self.setText(oldstr)
		self.__finished=True
		
	def __dataAvail(self, text):
		oldstr = self.getText() + "\n"
		if len(text):
			if text[0]=='w':
				oldstr += _("%sMB written in %.3fs") %(self.__testsize, float(text[1:])/1000)
			elif text[0]=='r':
				oldstr += _("%sMB read in %.3fs") %(self.__testsize, float(text[1:])/1000)
				oldstr += "\n\n%s %s" %(_("Remove"),_("testfile"))
			else:
				oldstr += "\n%s %s" %(_("Error"),text)
			self.setText(oldstr)

	def Exit(self):
		if self.__finished:
			self.Exitnow()
			
	def Exitnow(self):
		self.container.kill()
		del self.container
		self.close()
		cleanexit(__name__)

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

class TrafficInfo(gMessageBox):
	TRAFFICBINARY="/usr/bin/gtraffic"
	#TRAFFICBINARY="/root/bin/gtraffic"
	def __init__(self, session, name=None):
		gMessageBox.__init__ (self, session, title = name or _("Stream-Traffic"), icon="mess_trafficinfo.png")

		self.text = _("One moment please...")
		self.container = eConsoleAppContainer()
		self.container_dataAvail_conn = self.container.dataAvail.connect(self.__dataAvail)
		self.container_appClosed_conn = self.container.appClosed.connect(self.__finishedC)
		
		if self.session.nav.RecordTimer.isRecording() == False:
			service = self.session.nav.getCurrentService()
			if service is not None:
				
				demux = -1
				stream = service.stream()
				if stream:
					streamdata = stream.getStreamingData()
					demux = streamdata.get('demux', -1)
				info = service.info()
				if info and demux != -1:
					print "jojo"
					cmd = "%s %d %d %d" % (self.TRAFFICBINARY, demux, info.getInfo(iServiceInformation.sVideoPID), info.getInfo(iServiceInformation.sAudioPID))
					print cmd
					self.container.execute(cmd)
				else:
					self.text = _("Service not found")
		else:
			self.text = _("not by Record !")

		self.onLayoutFinish.append(self.__fillList)

	def __fillList(self):
		self.setText(self.text)

	def __dataAvail(self, text):
		list = text.split(" ")
		print list
		if len(list)== 5:
			ave = int(list[1]) + int(list[3])
			self.text = _("current Video\t") + list[0] + " kbit/s\n"
			self.text += _("current Audio\t") + list[2] + " kbit/s\n\n"
			self.text += _("average") + "\t" + str(ave) + " kbit/s"
			self.__fillList()

	def Exit(self):
		self.container.kill()
		self.__finishedC(False)
		
	def __finishedC(self, retval):
		del self.container
		self.close()
		cleanexit(__name__)

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

class GeminiConfList(WidgetVariableList):
	def __init__(self, session, name=None):
		
		WidgetVariableList.__init__ (self, session, title = name or _("Gemini Configuration"), list=[], icon="icon_geminiinfo.png", NameGreen=_("Save"))
		self.skinName = [self.__class__.__name__,"VList3Button2Entry_" + self.__class__.__name__,"VList3Button2Entry"]
		self.onLayoutFinish.append(self.__LayoutFinish)
		
	def __LayoutFinish(self):
		list=[]
		for x in libgeminimain.getPyList(GETCONFIGLIST):
			typ="%s = %s" %(_("Type"),"Integer")
			if x[0]:
				typ="%s = %s" %(_("Type"),"String")
			seppic=None
			if x[3]:
				seppic=ctoolsclass.getSeperatorPic()
			list.append((typ,None,x[1],seppic,str(x[2])))
		self.SetList(list)
		
	def selectionChanged(self):
		sel = self.getCurrentEntry()
		if sel:
			self.SetLabel(sel[4])
		
	def KeyGreen(self):
		libgeminimain.gFunktion(CONFIGFUNC,4)
		self.session.open(MessageBox, _("done..."), MessageBox.TYPE_INFO, timeout=3)
		
	def KeyExit(self):
		self.close()
		cleanexit(__name__)

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

class InfoCamdList(WidgetVariableList):
	def __init__(self, session, name=None):
		WidgetVariableList.__init__ (self, session, title = name or _("Installed Camds"), NameGreen=_("Reload list"), selectionEnabled=0, icon="icon_camdinfo.png")
		self.skinName = [self.__class__.__name__,"VList3Button2Entry_" + self.__class__.__name__,"VList3Button2Entry"]
		self.onLayoutFinish.append(self.__fillList)

	def __fillList(self):
		list=[]
		clist = libgeminimain.getPyList(GETCAMDLIST)
		for x in clist:
			list.append((_("Name"),None,x[2],None))
			list.append((_("Camd ID") ,None,str(x[0]),None))
			if x[1]==1:
				list.append((_("aktiv"),None,_("on"),ctoolsclass.getSeperatorPic()))
			else:
				list.append((_("aktiv"),None,_("off"),ctoolsclass.getSeperatorPic()))
		self.SetList(list)
		self.SetSelection(0)
		self.SetLabel(getEntryString(len(clist)))

	def KeyGreen(self):
		libgeminimain.gFunktion(CONFIGFUNC,1)
		self.session.open(MessageBox, _("done..."), MessageBox.TYPE_INFO, timeout=3)
		self.__fillList()

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

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

class showRoutes(WidgetVariableList):
	def __init__(self, session, libgtools):
		WidgetVariableList.__init__ (self, session, title = "Routes" , list=[], LinesProEntry=3, selectionEnabled=0)
		self.skinName = [self.__class__.__name__,"VariableListNoButton_" + self.__class__.__name__,"VariableListNoButton"]
		
		self.__routelist = libgtools.RouteInfos()
		self.onLayoutFinish.append(self.__fillListe)
	
	def __fillListe(self, what=0, val=""):
		self.hideLabel()
		list=[]
		for x in self.__routelist:
			text = _("Device") + ": " + x[0] + "\t\tFlags: " + x[4] + "\n"
			if x[1]=="0.0.0.0":
				text += "Destination: default"
			else:
				text += "Destination: " + x[1]
			if x[2]=="0.0.0.0":
				text += "\tGateway: *"
			else:
				text += "\tGateway: " + x[2]
			list.append((text, None))
		self.SetList(list)

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