# -*- coding: utf-8 -*-
from gLocale import _
from gTools import libgeminimain, cleanexit, getEntryString, pathExists
from WidgetVariableList import WidgetVariableList
from WidgetConfig import gConfigWindow,gConfigSelection, gConfigDirectory, CONFIGSEPERATOR

from enigma import eTimer
from Screens.MessageBox import MessageBox
from Components.config import config, NoSave, getConfigListEntry, ConfigText, ConfigInteger
from os import system as os_system

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

class SambaSetup(gConfigWindow):
	CONFIG_SAMBA = "/etc/samba/smb.conf"
	SAMBASTARTSCRIPT="/etc/init.d/samba"
	BINARYNAME = "smbd"

	def __init__(self, session, name=None):
		gConfigWindow.__init__ (self, session, name or _("Samba") + " " + _("Setup"), icon = "icon_samba.png", redbutton=_("Shares"))
		
		self.newconf=False
		self.__clock_timer = eTimer()
		
		if pathExists("/usr/sbin/" + self.BINARYNAME):
			self.onLayoutFinish.append(self.__createSetup)
		else:
			self.__clock_timer_conn = self.__clock_timer.timeout.connect(self.__installSamba)
			self.__clock_timer.start(300,True)
			
	def __installSamba(self):
		text = _("Package '%s' not installed!") %"samba"
		text += "\n" + _("Install package") + "?"
		self.session.openWithCallback(self.__CallbackInstall, MessageBox, text, MessageBox.TYPE_YESNO)
		
	def __CallbackInstall(self, result):
		if result:
			from WidgetIpkg import WidgetIpkg, IPKG_UPDATE, IPKG_INSTALL
			self.session.openWithCallback(self.__createSetup, WidgetIpkg, cmdList=[(IPKG_UPDATE,""), (IPKG_INSTALL,"samba")])
		
	def __createSetup(self,val=None):
		self.__clock_timer_conn = self.__clock_timer.timeout.connect(self.__SetLabel)
		
		from Plugins.Bp.geminimain.lib import libgtools
		self.conflist = libgtools.getSambaInfo(self.CONFIG_SAMBA)
		del libgtools
		
		if len(self.conflist) > 0 and self.conflist[0][0] == "global":
			conflist = []
			for x in self.conflist[0]:
				if not isinstance(x, list):
					continue
				if x[2] == 1:
					config.bp.val0 = NoSave(gConfigSelection(default=x[1], choices=[("no", _("no")), ("yes", _("yes"))]))
				elif x[2] == 2:
					config.bp.val0 = NoSave(ConfigInteger(default=int(x[1]), limits=(1, 99)))
				else:
					config.bp.val0 = NoSave(ConfigText(default=x[1], fixed_size=False))
				conflist.append(getConfigListEntry(x[0], config.bp.val0))
			self.SetConfList(conflist)
		self.__clock_timer.start(300)
		
	def __SetLabel(self):
		text = _("Samba") + "\n"
		if libgeminimain.isRunning(self.BINARYNAME):
			text += _("running")
		else:
			text += _("not running")
		self.SetLabel(text)
		self.__clock_timer.start(3000)
		
	def KeyRed(self):
		self.SetIndex(0)#wegen VirtualKeyboard
		self.session.openWithCallback(self.__backShareConfig, ShareConfig, self.conflist)
		
	def __backShareConfig(self, val=None):
		if val:
			self.newconf=True
			self.conflist=val
		
	def KeyExit(self):
		if self.ListChanged() or self.newconf:
			self.session.openWithCallback(self.__CallbackMB, MessageBox, _("Continue without saving?"), MessageBox.TYPE_YESNO)
		else:
			self.Exit()
			
	def __CallbackMB(self, val=None):
		if val:
			self.Exit()
			
	def KeyGreen(self):
		try:
			wfile = open(self.CONFIG_SAMBA, 'w')
	
			wfile.write("[global]\n")
			for x in self.getConfList():
				wfile.write("   " + x[0] + " = " + str(x[1].value) + "\n")

			for a in self.conflist:
				if a[0] != "global":
					wfile.write("\n")
					for b in a:
						if isinstance(b, str):
							wfile.write("[" + b + "]\n")
						else:
							wfile.write("   " + b[0] + " = " + b[1] + "\n")
			wfile.close()
			self.session.open(MessageBox, _("Values stored"), MessageBox.TYPE_INFO, 5)
			libgeminimain.sendDbus("gdaemon",0,self.SAMBASTARTSCRIPT + " restart")
			self.Exit()
		except:
			pass
		
	def Exit(self):
		del self.__clock_timer
		self.close(None)
		cleanexit(__name__)
 
#--------------------------------------------------------------------------------------

def createName(x):
	tstr = _("Name") + ": " + x[0]
	comment_str = ""
	path_str = ""
	for y in x:
		if y[0] == "comment":
			comment_str = "\n" + _("Description") + ": " + y[1]
		if y[0] == "path":
			path_str = "\n" + _("Path") + ": " + y[1]
		if y[0] == "read only" and y[1] == "no":
			path_str += " (rw)"
		if y[0] == "read only" and y[1] == "yes":
			path_str += " (ro)"
	return (tstr + comment_str + path_str)

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

class ShareConfig(WidgetVariableList):
	def __init__(self, session, sharelist):
		self.newconf=False
		self.shareglobal = []
		list = []
		for x in sharelist:
			if x[0] == "global":
				self.shareglobal = x
			else:
				list.append((createName(x), None, x))

		WidgetVariableList.__init__ (self, session, _("Shares"), LinesProEntry=3, NameRed=_("Delete"), NameGreen=_("Add"), icon="geminisambaconfig/icon_samba.png",list=list)
		self.skinName = [self.__class__.__name__,"VariableList3Button_" + self.__class__.__name__,"VariableList3Button"]
		self.onLayoutFinish.append(self.__updateText)
	
	def __updateText(self):
		self.SetLabel(getEntryString(len(self.GetList())))
		
	def KeyOk(self):
		val = self.getCurrentEntry()
		if val:
			self.session.openWithCallback(self.__Callbackedit, ShareSetup, val[2])
			
	def KeyGreen(self):
		self.session.openWithCallback(self.__Callbackadd, ShareSetup, [])

	def KeyRed(self):
		val = self.getCurrentEntry()
		if val:
			self.RemoveEntry(self.GetIndex())
			self.newconf=True
			self.__updateText()
		
	def __Callbackadd(self, val=None):
		if val:
			self.addEntry(val)
			self.newconf=True
			self.__updateText()

	def __Callbackedit(self, val=None):
		if val:
			self.editEntry(self.GetIndex(),val)
			self.newconf=True

	def KeyExit(self):
		if self.newconf:
			list = []
			if len(self.shareglobal):
				list.append(self.shareglobal)
			for x in self.GetList():
				list.append(x[2])
			self.close(list)
		else:
			self.close()

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

class ShareSetup(gConfigWindow):
	def __init__(self, session, share_entry):
		
		liste = []
		name_str = _("Name")
		command_str = ""
		read_only_str = "no"
		public_str = "yes"
		guest_str = "yes"
		path_dir = "/tmp"

		for x in share_entry:
			if isinstance(x, str):
				name_str = x
			if isinstance(x, list):
				if x[0] == "comment":
					command_str = x[1]
				if x[0] == "path":
					path_dir = x[1]
				if x[0] == "read only":
					read_only_str = x[1]
				if x[0] == "public":
					public_str = x[1]
				if x[0] == "guest ok":
					guest_str = x[1]
		if command_str == "":
			command_str = _("Description")
			
		config.bp.name = NoSave(ConfigText(default=name_str, fixed_size=False))
		config.bp.comment = NoSave(ConfigText(default=command_str, fixed_size=False))
		config.bp.path = NoSave(gConfigDirectory(default=path_dir))
		config.bp.read = NoSave(gConfigSelection(default=read_only_str, choices=[("no", _("no")), ("yes", _("yes"))]))
		config.bp.public = NoSave(gConfigSelection(default=public_str, choices=[("no", _("no")), ("yes", _("yes"))]))
		config.bp.guest = NoSave(gConfigSelection(default=guest_str, choices=[("no", _("no")), ("yes", _("yes"))]))
		
		liste.append(getConfigListEntry(_("Name") + ":", config.bp.name))
		liste.append(getConfigListEntry(_("Description") + ":", config.bp.comment))
		liste.append(CONFIGSEPERATOR())
		liste.append(getConfigListEntry(_("Path") + ": ", config.bp.path))
		liste.append(getConfigListEntry(_("read only") + ":", config.bp.read))
		liste.append(getConfigListEntry(_("public") + ":", config.bp.public))
		liste.append(getConfigListEntry(_("guest ok") + ":", config.bp.guest))

		gConfigWindow.__init__ (self, session, _("Share") + " '" + name_str + "'", icon="geminisambaconfig/icon_samba.png",list=liste)
		
	def KeyGreen(self):
		list = []
		list.append(config.bp.name.value)
		list.append(["comment", config.bp.comment.value, 0])
		list.append(["path", config.bp.path.value, 0])
		list.append(["read only", config.bp.read.value, 1])
		list.append(["public", config.bp.public.value, 1])
		list.append(["guest ok", config.bp.guest.value, 1])
		self.close((createName(list),None,list))
		
	def KeyExit(self):
		self.close()
