# -*- coding: utf-8 -*-
from gLocale import _
from GeminiDef import *
from gTools import libgeminimain, cleanexit, modulExists, createDirectory, pathRemove, pathExists
from WidgetVariableList import WidgetVariableList 

from enigma import eTimer
from Screens.MessageBox import MessageBox
from WidgetConfig import gConfigWindow, CONFIGSEPERATOR, gConfigSelection, gConfigOnOff
from Components.config import config, NoSave, getConfigListEntry, ConfigText, ConfigNothing

A_MPOINT=0
A_TYPE=1
A_USER=2
A_PASS=3
A_OPT=4
A_RSIZE=5
A_WSIZE=6
A_SERVER=7
A_SHARE=8
A_CHARSET=9
A_RETRY=10

def GetAText(list):
	text = _("Mountpoint") + ":\t" + "/media/network/" + list[A_MPOINT] + "\n"
	text += _("Type") + ":\t" + list[A_TYPE] + "\n"
	text += _("Parameters") + ":\t" + list[A_OPT] + "\n"
	text += _("Server") + ":\t" + list[A_SERVER] + "\n"
	text += _("Share") + ":\t" + list[A_SHARE]
	return text

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

class Automount(WidgetVariableList):
	MBFORSPEEDTEST = "100"
	AUTOMOUNT_CONF = "/etc/auto.gemini"

	def __init__(self, session, name=None, extEntry=None):
		self.__extEntry=extEntry
		self.newconf=False
		from lib import libgtools
		list=[]
		for x in libgtools.getAutomount(self.AUTOMOUNT_CONF, " "):
			#print x
			if isinstance(x, tuple):
				list.append((GetAText(x),None,x))
		del libgtools

		WidgetVariableList.__init__ (self, session, name or _("Automount Editor"), LinesProEntry=5, NameRed=_("Delete"), NameGreen=_("Add"), icon="icon_automount.png",list=list)
		self.skinName = [self.__class__.__name__,"VariableList3Button_" + self.__class__.__name__,"VariableList3Button"]
		self.onLayoutFinish.append(self.__checkAutoMaster)
		
	def KeyExit(self):
		if self.__saveConfig():
			self.session.open(MessageBox, _("Values stored"), MessageBox.TYPE_INFO, 5)
		self.close()
		cleanexit(__name__)
		
	def __checkAutoMaster(self):
		self.__updateText()

	def KeyOk(self):
		val = self.getCurrentEntry()
		if val and val[2]:
			self.session.openWithCallback(self.__Callbackedit, AutomountEntry, val[2])

	def KeyRed(self):
		val = self.getCurrentEntry()
		if val:
			self.RemoveEntry(self.GetIndex())
			self.newconf=True
			self.__updateText()
		
	def KeyGreen(self):
		val = [_("Mountname"), "nfs", _("Your_Username"), _("Your_Password"), "rw,nolock,soft,tcp","8192","8192", _("Name_or_IP"), _("Your_Share"), "", "0"]
		self.session.openWithCallback(self.__Callbackappend, AutomountEntry, val)
		
	def __Callbackappend(self, res = False):
		if res:
			self.addEntry(res)
			self.newconf=True
			self.__updateText()
			
	def __Callbackedit(self, res = False):
		if res:
			self.editEntry(self.GetIndex(),res)
			self.newconf=True
			self.__updateText()
			
	def __updateText(self):
		if len(self.GetList()):
			self.SetBB(_("speed test"))
		else:
			self.SetBB()

		if self.__extEntry is not None:
			self.__extTimer = eTimer()
			self.__extTimer_conn = self.__extTimer.timeout.connect(self.__StartExtEntry)
			self.__extTimer.start(300,True)
			
	def __StartExtEntry(self):
		self.session.openWithCallback(self.__Callbackappend, AutomountEntry, self.__extEntry)
		self.__extEntry=None
		
	def __saveConfig(self):
		if self.newconf:
			try:
				fp = file(self.AUTOMOUNT_CONF, 'w')
				fp.write("# generated by gemini \n")
				for x in self.GetList():
					y = x[2]
					text = y[A_MPOINT] + " -fstype=" + y[A_TYPE] + "," + y[A_OPT]
					if y[A_RSIZE] != "":
						text += ",rsize=" + y[A_RSIZE]
					if y[A_WSIZE] != "":
						text += ",wsize=" + y[A_WSIZE]
					if y[A_USER] != "" and y[A_PASS] != "":
						text += ",user=" + y[A_USER] + ",pass=" + y[A_PASS]
					if y[A_CHARSET] != "":
						text += ",iocharset=" + y[A_CHARSET]
			
					if y[A_TYPE] == "nfs":
						if y[A_RETRY] == "1":
							text += ",retry=1"
						else:
							text += ",retry=0"
						text += " " + y[A_SERVER] + ":/" + y[A_SHARE]
					else:
						text += " ://" + y[A_SERVER] + "/" + y[A_SHARE]
					fp.write(text + "\n")
				fp.close()
				libgeminimain.sendDbus("gdaemon",0,"systemctl restart autofs")
				self.newconf=False
				return True
			except:
				pass
		return False

	def __startSpeedTest(self):
		val = self.getCurrentEntry()
		if val and val[2]:
			mpoint = "/media/network/" + val[2][A_MPOINT]
			testdir = mpoint + "/01_bla_bla_02"
			mountfound=False
			if createDirectory(self,testdir):#testen ob man schreiben kann
				if pathRemove(testdir)==0:
					for x in libgeminimain.getPyList(GETMOUNTLIST):
						if mpoint == x[PART_MPOINT] and x[PART_FS_TYPE] == FS_AUTO:
							mountfound=True
							break
			
				if mountfound==False:
					self.session.open(MessageBox, _("Failed mount by '%s'") %mpoint, MessageBox.TYPE_ERROR, timeout=5)
				else:
					
					from InfoScreens import SpeedcheckInfo
					self.session.open(SpeedcheckInfo, mpoint + "/.speedtestfile", self.MBFORSPEEDTEST)

	def KeyBlue(self):
		if self.__saveConfig():
			self.__saveTimer = eTimer()
			self.__saveTimer_conn = self.__saveTimer.timeout.connect(self.__startSpeedTest)
			self.__saveTimer.start(2000,True)
		else:
			self.__startSpeedTest()

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

class AutomountEntry(gConfigWindow):
	def __init__(self, session, list):
		gConfigWindow.__init__(self, session, icon="icon_automount.png")
		self.selected=0
		self.optstr = list[A_OPT]
		#print list
		sizel=[_("off")]
		retry=0
		if list[A_RETRY]=="1":
			retry=1
		val=2048
		for x in range(6):#range for Buffer
			val=val*2
			sizel.append(str(val))
		filefs=["nfs"]
		if modulExists("fs/cifs"):
			filefs.append("cifs")
		if modulExists("fs/smbfs"):
			filefs.append("smbfs")
		config.bp.mp = NoSave(ConfigText(default=list[A_MPOINT], fixed_size=False))
		config.bp.typ = NoSave(gConfigSelection(default=list[A_TYPE], choices=filefs))
		config.bp.opt = NoSave(ConfigNothing())
		config.bp.user = NoSave(ConfigText(default=list[A_USER], fixed_size=False))
		config.bp.pas = NoSave(ConfigText(default=list[A_PASS], fixed_size=False))
		config.bp.rsize = NoSave(gConfigSelection(default=list[A_RSIZE], choices=sizel))
		config.bp.wsize = NoSave(gConfigSelection(default=list[A_WSIZE], choices=sizel))
		config.bp.server = NoSave(ConfigText(default=list[A_SERVER], fixed_size=False))
		config.bp.share = NoSave(ConfigText(default=list[A_SHARE], fixed_size=False))
		config.bp.charset = NoSave(ConfigText(default=list[A_CHARSET], fixed_size=False))
		config.bp.retry = NoSave(gConfigOnOff(default=retry))
		self.__fillList()
		
	def SelectionChangedNow(self):
		gConfigWindow.SelectionChangedNow(self)
		self.setRB()
		self.selected=0
		sel = self.getCurrendValue()
		if sel:
			if sel == config.bp.opt:
				self.setRB(_("Edit"))
				self.selected=1

	def __fillList(self):
		list = []
		list.append(getConfigListEntry(_("Name (Please write without / on beginning)"), config.bp.mp))
		list.append(getConfigListEntry(_("Type"), config.bp.typ))
		list.append(getConfigListEntry(_("Parameters")+":\t" + self.optstr, config.bp.opt))
		list.append(CONFIGSEPERATOR())
		list.append(getConfigListEntry(_("Server"), config.bp.server))
		list.append(getConfigListEntry(_("Share (Please write without / on beginning)"), config.bp.share))
		list.append(CONFIGSEPERATOR())
		list.append(getConfigListEntry(_("Read-Buffer"), config.bp.rsize))
		list.append(getConfigListEntry(_("Write-Buffer"), config.bp.wsize))
		if config.bp.typ.value == "nfs":
			list.append(getConfigListEntry(_("Retry"), config.bp.retry))
		if config.bp.typ.value != "nfs": 
			list.append(CONFIGSEPERATOR())
			list.append(getConfigListEntry(_("User"), config.bp.user))
			list.append(getConfigListEntry(_("Password"), config.bp.pas))
			list.append(getConfigListEntry(_("Charset (utf8)"), config.bp.charset))

		self.SetConfList(list)
		
	def KeyOk(self):
		if self.selected==1:
			self.KeyRed()
		else:
			gConfigWindow.KeyOk(self)
		
	def KeyRed(self):
		if self.selected==1:
			self.session.openWithCallback(self.__CallbackPara, ParaSetup, self.optstr.split(',') or [])
			
	def __CallbackPara(self, val=None):
		if val is not None:
			self.optstr = val
			self.__fillList()

	def KeyLeft(self):
		gConfigWindow.KeyLeft(self)
		if self.getCurrendValue() == config.bp.typ:
			self.__fillList()

	def KeyRight(self):
		gConfigWindow.KeyRight(self)
		if self.getCurrendValue() == config.bp.typ:
			self.__fillList()

	def KeyGreen(self):
		list = ["","","","","","","","","","","",""]
		list[A_MPOINT] = config.bp.mp.value.replace(" ", "")
		list[A_TYPE] = config.bp.typ.value
		list[A_OPT] = self.optstr
		if config.bp.typ.value != "nfs":
			list[A_USER] = config.bp.user.value.replace(" ", "")
			list[A_PASS] = config.bp.pas.value.replace(" ", "")
		if config.bp.rsize.value != _("off"):
			list[A_RSIZE] = config.bp.rsize.value
		if config.bp.wsize.value != _("off"):
			list[A_WSIZE] = config.bp.wsize.value
		list[A_SERVER] = config.bp.server.value.replace(" ", "")
		list[A_SHARE] = config.bp.share.value.replace(" ", "")
		list[A_CHARSET] = config.bp.charset.value.replace(" ", "")
		list[A_RETRY] = "0"
		if config.bp.retry.value:
			list[A_RETRY] = "1"
		#print "Green",list
		self.close((GetAText(list),None,list))

	def KeyExit(self):
		self.close()


class ParaSetup(gConfigWindow):
	def __init__(self, session, paralist):
		#print paralist
		list=[]
		is_rw=0
		is_soft=0
		is_nolock=0
		typ=_("off")
		charset=_("off")
		for x in paralist:
			#print x
			if x=="rw":
				is_rw=1
			elif x=="soft":
				is_soft=1
			elif x=="nolock":
				is_nolock=1
			elif x=="udp":
				typ="udp"
			elif x=="tcp":
				typ="tcp"

		config.bp.rw = NoSave(gConfigOnOff(default=is_rw))
		config.bp.soft = NoSave(gConfigOnOff(default=is_soft))
		config.bp.nolock = NoSave(gConfigOnOff(default=is_nolock))
		config.bp.networktyp = NoSave(gConfigSelection(default=typ, choices=[_("off"),"udp","tcp"]))
		
		list.append(getConfigListEntry(_("read/write"), config.bp.rw))
		list.append(getConfigListEntry("soft", config.bp.soft))
		list.append(getConfigListEntry("nolock", config.bp.nolock))
		list.append(getConfigListEntry(_("networkprotocol"), config.bp.networktyp))
		
		gConfigWindow.__init__(self, session, _("Parameters")+" "+_("Setup"), list = list)
		
	def KeyGreen(self):
		optstr=""
		if config.bp.rw.value:
			optstr+="rw"
		else:
			optstr+="ro"
		if config.bp.soft.value:
			optstr+=",soft"
		if config.bp.nolock.value:
			optstr+=",nolock"
		if config.bp.networktyp.value != _("off"):
			optstr+=","+config.bp.networktyp.value
		
		self.close(optstr)

	def KeyExit(self):
		self.close()
