# options.py
# 
# Copyright (C) 2008 Stefan Betz <stefan_betz@gmx.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import pygtk
pygtk.require('2.0')
import gtk
import string
import gettext
from stat import S_ISUID, ST_MODE
from os import stat
from pyneighborhood import config
from pyneighborhood.misc import unpad, sharepath, homeconfdir
from pyneighborhood.events import browsingevent

_ = gettext.gettext

class OptionsDialog(object):
    """
    Class for the options-dialog
    """
    def path_validator(self, path):
        """
        Fix the entered path
        """
        list = path.split("/")
        final_path = ""
        for item in list:
            if item != "":
                final_path = final_path + "/" + item
        return final_path

    def response_handler(self, widget, response_id):
        """
        Dialog Callback for the respone...
        """
        if response_id == gtk.RESPONSE_CANCEL:
            self.window.destroy()
            return gtk.FALSE
        elif response_id == gtk.RESPONSE_APPLY:
            config.set("CIFS", "mount", unpad(self.cifs_mount.get_text()))
            config.set("CIFS", "options", unpad(self.cifs_options.get_text()))
            config.set("CIFS", "unmount", unpad(self.cifs_umount.get_text()))
            # Main Options
            config.set("Main", "cleanup_dirs", str(self.mountpoint_cleanup.get_active()))
            config.set("Main", "enable_file_manager", str(self.launch_filemanager.get_active()))
            config.set("Main", "filemanager", str(self.filemanager.get_text()))
            config.set("Main", "mount_directory", self.path_validator(unpad(self.mountpoint.get_text())))
            config.set("Main", "password", unpad(self.password.get_text()))
            config.set("Main", "username", unpad(self.username.get_text()))
            config.set("Main", "enable_sudo", str(self.sudo_toggle.get_active()))
            config.set("Main", "sudo", unpad(self.sudoentry.get_text()))
            config.set("Main", "loglevel", str(self.loglevels.get_value(self.loglevelentry.get_active_iter(), 0)))
            config.set("Main", "hidden_shares", str(self.hiddenshares.get_active()))
            f = open(homeconfdir() + "/config", "w")
            config.write(f)
            f.flush()
            f.close()
            browsingevent.set() 
            self.window.destroy()
            return gtk.TRUE

    def launch_filemanager_toggle(self, widget):
        """
        Enables or disables the filemanager entry
        """
        if self.launch_filemanager.get_active() == True:
            self.filemanager.set_sensitive(True)
        else:
            self.filemanager.set_sensitive(False)

    def sudo_toggled(self, widget):
        """
        Enables or disables the sudo entry
        """
        if self.sudo_toggle.get_active():
            self.sudoentry.set_sensitive(True)
        else:
            if ((stat(config.get("CIFS", "mount"))[ST_MODE] & S_ISUID) == 0) or ((stat(config.get("CIFS", "unmount"))[ST_MODE] & S_ISUID) == 0):
                self.sudo_toggle.set_active(True)
                dlg = gtk.MessageDialog(self.window, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("SUID bits on mount/umount are not set!\nDisabling sudo is not possible!"))
                dlg.connect("response", lambda x,y: dlg.destroy())
                dlg.run()
                return
            self.sudoentry.set_sensitive(False)

    def __init__(self, parent):
        """
        Constructor, creates the Windows and many more...
        """
        self.parent = parent
        
        self.xml = gtk.Builder()
        self.xml.set_translation_domain('pyNeighborhood')
        self.xml.add_from_file(sharepath('ui/options.glade') )
        self.xml.connect_signals(self)
        
        self.window = self.xml.get_object("options")
        
        # CIFS Options
        self.cifs_mount = self.xml.get_object("cifsmount")
        self.cifs_mount.set_text(config.get("CIFS", "mount"))
        self.cifs_umount = self.xml.get_object("cifsumount")
        self.cifs_umount.set_text(config.get("CIFS", "unmount"))
        self.cifs_options = self.xml.get_object("cifsoptions")
        self.cifs_options.set_text(config.get("CIFS", "options"))
        # Mounpoint Options
        self.mountpoint = self.xml.get_object("mountpoint-entry")
        self.mountpoint.set_text(config.get("Main", "mount_directory"))
        self.mountpoint_cleanup = self.xml.get_object("mountpoint-cleanup")
        if config.get("Main", "cleanup_dirs") == "True":
            self.mountpoint_cleanup.set_active(True)
        else:
            self.mountpoint_cleanup.set_active(False)
        # Login Options
        self.username = self.xml.get_object("username-entry")
        self.username.set_text(config.get("Main", "username"))
        self.password = self.xml.get_object("password-entry")
        self.password.set_text(config.get("Main", "password"))
        # Filemanager Options
        self.launch_filemanager = self.xml.get_object("options-launch-filemanager")
        self.filemanager = self.xml.get_object("options-filemanager-entry")
        self.filemanager.set_text(config.get("Main", "filemanager"))
        if config.get("Main", "enable_file_manager") == "True":
            self.launch_filemanager.set_active(True)
            self.filemanager.set_sensitive(True)
        else:
            self.launch_filemanager.set_active(False)
            self.filemanager.set_sensitive(False)
        # Sudo Options
        self.sudo_toggle = self.xml.get_object("options-use-sudo")
        self.sudoentry = self.xml.get_object("sudo-entry")
        self.sudoentry.set_text(config.get("Main", "sudo"))
        if config.get("Main", "enable_sudo") == "True":
            self.sudo_toggle.set_active(True)
            self.sudoentry.set_sensitive(True)
        else:
            self.sudo_toggle.set_active(False)
            self.sudoentry.set_sensitive(False)
        # Loglevel Options
        self.loglevelentry = self.xml.get_object("loglevel-entry")
        self.loglevels = gtk.ListStore(int, str)
        self.loglevels.append([-1, 'Nothing'])
        self.loglevels.append([0, 'All'])
        self.loglevels.append([1, 'Warnings and Errors'])
        self.loglevels.append([2, 'Only Errors'])
        self.loglevelentry.set_model(self.loglevels)
        loglevelcell = gtk.CellRendererText()
        self.loglevelentry.pack_start(loglevelcell, True)
        self.loglevelentry.add_attribute(loglevelcell, 'text', 1)
        for loglevel in self.loglevels:
            if loglevel[0] == int(config.get("Main","loglevel")):
                self.loglevelentry.set_active_iter(loglevel.iter)
        # Hidden Shares Options
        self.hiddenshares = self.xml.get_object("hidden-shares")
        if config.get('Main','hidden_shares') == 'True':
            self.hiddenshares.set_active(True)
