# -*- coding: utf-8 -*-
from gLocale import _
from gTools import libgeminimain, cleanexit
from plugin import cgevent, dbusNotifier

from WidgetConfig import gConfigSelection, gConfigWindow, gConfigOnOff
from Screens.Console import Console
from Components.config import config, NoSave, getConfigListEntry, ConfigText

class confOnlineTest(gConfigWindow):
	GDAEMONONLINETEST=1
	def __init__(self, session, name=None):
		self.selected=0
		self.__checkOnline=False
		config.bp.onoff = NoSave(gConfigOnOff(default=cgevent.getConfig("ping_server", 0)))
		config.bp.server = NoSave(ConfigText(default=cgevent.getConfig("ping_server", "google.com"), fixed_size=False))
		
		list = []
		list.append(getConfigListEntry(_("enable") + " ?", config.bp.onoff))
		list.append(getConfigListEntry(_("Server") + ":", config.bp.server))

		gConfigWindow.__init__ (self, session, name or _("Online Test"), list=list, icon="icon_onlinetest.png", setSkin="Config3Button")
		dbusNotifier.append(("gdaemon", self.__OnlineCheck))
	
	def KeyExit(self):
		dbusNotifier.remove(("gdaemon", self.__OnlineCheck))
		self.close()
		cleanexit(__name__)

	def SelectionChangedNow(self):
		gConfigWindow.SelectionChangedNow(self)
		self.__checkEntry()
		
	def KeyLeft(self):
		gConfigWindow.KeyLeft(self)
		self.__checkEntry()

	def KeyRight(self):
		gConfigWindow.KeyRight(self)
		self.__checkEntry()
		
	def __checkEntry(self):
		self.selected=0
		self.setRB()
		sel = self.getCurrendValue()
		if sel == config.bp.onoff:
			if config.bp.onoff.value == True:
				self.selected=1
				self.setRB(_("Test"))
				self.setBB(_("speed test"))
	
	def KeyRed(self):
		if self.selected:
			self.SetLabel(_("unsuccessful") + "\n" + _("Please wait..."))
			self.__saveValue()

	def KeyGreen(self):
		self.__saveValue()
		self.KeyExit()
		
	def KeyBlue(self):
		self.__checkOnline=True
		self.KeyRed()
		
	def __saveValue(self):
		cgevent.setConfig("ping_server", config.bp.onoff.value)
		cgevent.setConfig("ping_server", config.bp.server.value)
		if config.bp.onoff.value == True:
			libgeminimain.sendDbus("gdaemon",self.GDAEMONONLINETEST, config.bp.server.value)
		else:
			libgeminimain.sendDbus("gdaemon",self.GDAEMONONLINETEST, "off")
	
	def __OnlineCheck(self, func, value):
		if func==self.GDAEMONONLINETEST:
			#print "__________________________________",func,value
			if value=="ONLINE":
				self.SetLabel(_("successfully"))
				if self.__checkOnline:
					self.__checkOnline=False
					self.session.open(Console, cmdlist = ["/usr/bin/gspeedtest.py"])
			else:
				self.SetLabel(_("unsuccessful") + "\n" + _("Please wait..."))

