from PyQt4 import QtGui, uic
from PyQt4.QtCore import *
from AttributeWidgets import *
from lechat.LDAPMapping import *
#from zope.interface import implements
#from twisted.python import components
from logging import warning, debug, critical

class ObjectClassWidget(QtGui.QWidget):
    
    def __init__(self, ui):
        QtGui.QWidget.__init__(self)

        self.ui = ui
        self.ui.parent.widget.tabs.addTab(self, 'config')

        self.setObjectName("config")
        self.resize(QSize(QRect(0,0,587,792).size()).expandedTo(self.minimumSizeHint()))
        self.setWindowIcon(QtGui.QIcon(":/lechat/resources/users.png"))

        self.main_layout = QtGui.QVBoxLayout(self)
        self.main_layout.setMargin(9)
        self.main_layout.setSpacing(6)
        self.main_layout.setObjectName("main_layout")

        self.scroll_area = QtGui.QScrollArea(self)
        self.scroll_area.setWidgetResizable(True)

        self.frame = QtGui.QFrame(self.scroll_area)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(QtGui.QSizePolicy.Expanding),
                                       QtGui.QSizePolicy.Policy(QtGui.QSizePolicy.Expanding))
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setFrameShape(QtGui.QFrame.NoFrame)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName("frame")

        self.scroll_area.setWidget(self.frame)
        
        self.frame_layout = QtGui.QVBoxLayout(self.frame)
        self.frame_layout.setMargin(9)
        self.frame_layout.setSpacing(6)
        self.frame_layout.setObjectName("frame_layout")

        self.edit_fields = {}
        
        attrs = [ (k, v) for k, v in self.ui.values.items() ]
        attrs.sort( key=lambda x: x[1].rank )
        
        for (k, v) in attrs:

            if not v.visible:
                self.edit_fields[k] = StaticWidget(self.frame)
                self.edit_fields[k].setData(v.value)
                continue
            
            hboxlayout = QtGui.QHBoxLayout()
            
            label = QtGui.QLabel(self.frame)
            label.setObjectName(k + "-label")
            label.setText( QString( _(k) ) )
            hboxlayout.addWidget(label)

            if v.attribute_type.multi_valued:
                w = MultiValuedWidget(self.frame)
            elif isinstance(v.attribute_type, BooleanAttribute):
                w = BooleanWidget(self.frame)
            elif isinstance(v.attribute_type, TextAttribute):
                w = TextWidget(self.frame)
            elif isinstance(v.attribute_type, PasswordAttribute):
                w = PasswordWidget(self.frame)
            elif isinstance(v.attribute_type, DNAttribute):
                w = DNWidget(self.frame, self.ui.parent, v.filter_re)
            elif isinstance(v.attribute_type, MailAttribute):
                w = MailWidget(self.frame)
            else:
                w = LineWidget(self.frame)

            if v.value:
                w.setData(v.value)
            self.edit_fields[k] = w
            hboxlayout.addWidget(w.widget)

            self.frame_layout.addLayout(hboxlayout)
        
        self.main_layout.addWidget(self.scroll_area)

        button_box = QtGui.QDialogButtonBox(self.frame)
        button_box.setOrientation(Qt.Horizontal)
        button_box.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.NoButton|QtGui.QDialogButtonBox.Ok)
        button_box.setObjectName("button_box")

        self.main_layout.addWidget(button_box)

        QObject.connect(button_box,SIGNAL("accepted()"), self.accept)
        QObject.connect(button_box,SIGNAL("rejected()"), self.reject)

    def accept(self):
        self.ui.parent.widget.tabs.removeTab( self.ui.parent.widget.tabs.indexOf(self) )

        for k, attr in self.ui.values.items():
            if attr and self.edit_fields.has_key(k):
                w = self.edit_fields[k]

                result = w.getData()

                if attr.value != result:
                    print '%s -> %s' %(attr.value, result)
                    attr.value = result
                    
        self.ui.modified.raiseEvent()

    def reject(self):
        self.ui.parent.widget.tabs.removeTab( self.ui.parent.widget.tabs.indexOf(self) )
        self.ui.canceled.raiseEvent()

    def show(self):
        self.ui.parent.widget.tabs.setCurrentWidget(self)
        self.edit_fields['node'].widget.setFocus()

    def setData(self, values):
        """
        Sets widget data, given a dictionnary of values, keyed by field name.
        """
        for k, attr in values.items():
            if self.edit_fields.has_key(k) and attr.value:
                w = self.edit_fields[k]
                w.setData(attr.value)
            
        self.ui.parent.widget.tabs.setTabText(self.ui.parent.widget.tabs.indexOf(self),
                                              str(values['node'].value[0]) )

    def getData(self):
        """
        Actualise ui's object values from widget.

        Returns a dictionnary of Attribute objects keyed by attribute name.
        """
        result = {}
        for k, attr in self.ui.values.items():
            if self.edit_fields.has_key(k):
                w = self.edit_fields[k]
                value = w.getData()
                if value:
                    result[k] = value
        return result

                            
#components.registerAdapter(
#    ObjectClassWidget,
#    Attribute,
#    ILechatWidget)

