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

# Copyright (c) 2006 - 2007 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the Debugger General (1) configuration page.
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtNetwork import *

from KdeQt import KQInputDialog, KQMessageBox

from ConfigurationPageBase import ConfigurationPageBase
from Ui_DebuggerGeneral1Page import Ui_DebuggerGeneral1Page

import Preferences
import Utilities

class DebuggerGeneral1Page(ConfigurationPageBase, Ui_DebuggerGeneral1Page):
    """
    Class implementing the Debugger General (1) configuration page.
    """
    def __init__(self):
        """
        Constructor
        """
        ConfigurationPageBase.__init__(self)
        self.setupUi(self)
        self.setObjectName("DebuggerGeneral1Page")
        
        t = self.execLineEdit.whatsThis()
        if not t.isEmpty():
            t.append(Utilities.getPercentReplacementHelp())
            self.execLineEdit.setWhatsThis(t)
        
        # set initial values
        interfaces = QStringList()
        networkInterfaces = QNetworkInterface.allInterfaces()
        for networkInterface in networkInterfaces:
            interfaceStr = QString("%1 (").arg(networkInterface.name())
            addressEntries = networkInterface.addressEntries()
            if len(addressEntries) > 0:
                for addressEntry in addressEntries:
                    interfaceStr.append(QString("%1, ").arg(addressEntry.ip().toString()))
                interfaceStr.replace(interfaceStr.length()-2, 2, ")")
                interfaces.append(interfaceStr)
        self.interfacesCombo.addItems(interfaces)
        interface = Preferences.getDebugger("NetworkInterface")
        if interface == "all":
            self.allInterfacesButton.setChecked(True)
        else:
            self.selectedInterfaceButton.setChecked(True)
            index = interfaces.indexOf(QRegExp(QString(".*%1.*").arg(interface)))
            self.interfacesCombo.setCurrentIndex(index)
        self.allowedHostsList.addItems(\
            Preferences.getDebugger("AllowedHosts"))
        self.remoteCheckBox.setChecked(\
            Preferences.getDebugger("RemoteDbgEnabled"))
        self.hostLineEdit.setText(\
            Preferences.getDebugger("RemoteHost"))
        self.execLineEdit.setText(\
            Preferences.getDebugger("RemoteExecution"))
        self.passiveDbgCheckBox.setChecked(\
            Preferences.getDebugger("PassiveDbgEnabled"))
        self.passiveDbgPortSpinBox.setValue(\
            Preferences.getDebugger("PassiveDbgPort"))
        
    def save(self):
        """
        Public slot to save the Debugger General (1) configuration.
        """
        Preferences.setDebugger("RemoteDbgEnabled", 
            int(self.remoteCheckBox.isChecked()))
        Preferences.setDebugger("RemoteHost", 
            self.hostLineEdit.text())
        Preferences.setDebugger("RemoteExecution", 
            self.execLineEdit.text())
        Preferences.setDebugger("PassiveDbgEnabled", 
            int(self.passiveDbgCheckBox.isChecked()))
        Preferences.setDebugger("PassiveDbgPort", 
            self.passiveDbgPortSpinBox.value())
        if self.allInterfacesButton.isChecked():
            Preferences.setDebugger("NetworkInterface", "all")
        else:
            interface = self.interfacesCombo.currentText()
            interface = interface.section("(",1,1).section(")",0,0).split(",")[0]
            if interface.isEmpty():
                Preferences.setDebugger("NetworkInterface", "all")
            else:
                Preferences.setDebugger("NetworkInterface", interface)
        allowedHosts = QStringList()
        for row in range(self.allowedHostsList.count()):
            allowedHosts.append(self.allowedHostsList.item(row).text())
        Preferences.setDebugger("AllowedHosts", allowedHosts)
        
    def on_allowedHostsList_currentItemChanged(self, current, previous):
        """
        Private method set the state of the edit and delete button.
        
        @param current new current item (QListWidgetItem)
        @param previous previous current item (QListWidgetItem)
        """
        self.editAllowedHostButton.setEnabled(current is not None)
        self.deleteAllowedHostButton.setEnabled(current is not None)
        
    @pyqtSignature("")
    def on_addAllowedHostButton_clicked(self):
        """
        Private slot called to add a new allowed host.
        """
        allowedHost, ok = KQInputDialog.getText(\
            None,
            self.trUtf8("Add allowed host"),
            self.trUtf8("Enter the IP address of an allowed host"),
            QLineEdit.Normal)
        if ok and not allowedHost.isEmpty():
            if QHostAddress(allowedHost).protocol() in \
               [QAbstractSocket.IPv4Protocol, QAbstractSocket.IPv6Protocol]:
                self.allowedHostsList.addItem(allowedHost)
            else:
                KQMessageBox.critical(None,
                    self.trUtf8("Add allowed host"),
                    self.trUtf8("""<p>The entered address <b>%1</b> is not"""
                        """ a valid IP v4 or IP v6 address. Aborting...</p>""")\
                        .arg(allowedHost))
        
    @pyqtSignature("")
    def on_deleteAllowedHostButton_clicked(self):
        """
        Private slot called to delete an allowed host.
        """
        self.allowedHostsList.takeItem(self.allowedHostsList.currentRow())
        
    @pyqtSignature("")
    def on_editAllowedHostButton_clicked(self):
        """
        Private slot called to edit an allowed host.
        """
        allowedHost = self.allowedHostsList.currentItem().text()
        allowedHost, ok = KQInputDialog.getText(\
            None,
            self.trUtf8("Edit allowed host"),
            self.trUtf8("Enter the IP address of an allowed host"),
            QLineEdit.Normal,
            allowedHost)
        if ok and not allowedHost.isEmpty():
            if QHostAddress(allowedHost).protocol() in \
               [QAbstractSocket.IPv4Protocol, QAbstractSocket.IPv6Protocol]:
                self.allowedHostsList.currentItem().setText(allowedHost)
            else:
                KQMessageBox.critical(None,
                    self.trUtf8("Edit allowed host"),
                    self.trUtf8("""<p>The entered address <b>%1</b> is not"""
                        """ a valid IP v4 or IP v6 address. Aborting...</p>""")\
                        .arg(allowedHost))
    
def create(dlg):
    """
    Module function to create the configuration page.
    
    @param dlg reference to the configuration dialog
    """
    page = DebuggerGeneral1Page()
    return page
