
from qt import *
import os.path
import ldap

import environment
from base.backend.ServerList import ServerList
from base.backend.LumaConnection import LumaConnection
from base.backend.SmartDataObject import SmartDataObject
from base.backend.ObjectClassAttributeInfo import ObjectClassAttributeInfo
from base.utils import lumaStringDecode, lumaStringEncode
from base.utils.gui.LumaErrorDialog import LumaErrorDialog
from plugins.usermanagement import addPreProcess, addPostProcess
from plugins.usermanagement.GroupWizardDesign import GroupWizardDesign
#from plugins.usermanagement.UsermanagementWidget import UsermanagementWidget

from base.utils.gui.BrowserWidget import BrowserWidget

class GroupWizard(GroupWizardDesign):

    def __init__(self,parent = None,name = None,modal = 0,fl = 0):
        GroupWizardDesign.__init__(self,parent,name,modal,fl)

        self.iconPath = os.path.join (environment.lumaInstallationPrefix, "share", "luma", "icons")
        iconDir = os.path.join (environment.lumaInstallationPrefix, "share", "luma", "icons","plugins", "addressbook")
        locationIcon = QPixmap (os.path.join (iconDir, "location.png"))
        self.locationLabel.setPixmap(locationIcon)

        layout = QHBoxLayout(self.browserFrame)
        self.browserWidget = BrowserWidget(self.browserFrame)
        layout.addWidget(self.browserWidget)

        # What does these do?
        self.connect(self.browserWidget, PYSIGNAL("ldap_result"), self.updateLocation)
        #self.connect(self.finishButton(), SIGNAL("clicked()"), self.saveContact)

        self.locationServer = None
        print "asdf"
        self.locationDN = None
        print "asdf"
        self.serverMeta = None
        print "asdf"

        for x in range(0,self.pageCount()):
            self.setHelpEnabled(self.page(x), 0)

        print "asdf"
        self.setFinishEnabled(self.page(1), 1)
        #self.disconnect(self.finishButton(), SIGNAL("clicked()"), self, SLOT("accept()"))
        #self.disconnect(self.nextButton(), SIGNAL("clicked()"), self, SLOT("next()"))

        self.connect(self.nextButton(),SIGNAL("clicked()"), self.checkNext)


        #self.accountWidget = UsermanagementWidget(self.accountFrame)
        #tmpLayout = QHBoxLayout(self.accountFrame)
        #tmpLayout.addWidget(self.accountWidget)

        print "asdf"

        #self.accountWidget.NEWENTRY = True

        #self.accountWidget.uidEdit.setReadOnly(False)
        #self.disconnect(self.accountWidget.groupButton, SIGNAL("clicked()"), self.accountWidget.editGroups)
        #self.connect(self.accountWidget.groupButton, SIGNAL("clicked()"), self.checkUID)
        #self.accountWidget.setEnabled(1)
        print "asdf"


###############################################################################

    def saveContact(self):
        dataObject = self.accountWidget.dataObject

        if not dataObject.hasAttribute('cn'):
            tmpDialog = QMessageBox(self.trUtf8("Save group"),
                self.trUtf8("Please enter a groupname."),
                QMessageBox.Critical,
                QMessageBox.Ok,
                QMessageBox.NoButton,
                QMessageBox.NoButton,
                self)

            tmpDialog.setIconPixmap(QPixmap(os.path.join(self.iconPath, "warning_big.png")))
            tmpDialog.exec_loop()
            return

        if not dataObject.hasAttribute('gidNumber'):
            tmpDialog = QMessageBox(self.trUtf8("Save group"),
                self.trUtf8("Please assign the group a posix group id."),
                QMessageBox.Critical,
                QMessageBox.Ok,
                QMessageBox.NoButton,
                QMessageBox.NoButton,
                self)

            tmpDialog.setIconPixmap(QPixmap(os.path.join(self.iconPath, "warning_big.png")))
            tmpDialog.exec_loop()
            return

        dn = "cn=" + dataObject.getAttributeValue('cn', 0) + "," + self.locationDN
        dataObject.setDN(dn)
        dataObject.addAttributeValue("cn", [dataObject.getAttributeValue("cn", 0)])

        # Start preprocessing of usercreation
        groupName = unicode(self.accountWidget.groupEdit.text())
        addPreProcess(self.serverMeta, dataObject.getDN(), dataObject.data, groupName)

        connectionObject = LumaConnection(self.serverMeta)
        bindSuccess, exceptionObject = connectionObject.bind()

        if not bindSuccess:
                dialog = LumaErrorDialog()
                errorMsg = self.trUtf8("Could not bind to server.<br><br>Reason: ")
                errorMsg.append(str(exceptionObject))
                dialog.setErrorMessage(errorMsg)
                dialog.exec_loop()
                return

        addSuccess, exceptionObject = connectionObject.addDataObject(dataObject)

        if addSuccess:
            #self.accountWidget.saveOtherGroups()

            # Start postprocessing of groupcreation
            addPostProcess(self.serverMeta, dataObject.getDN(), dataObject.data, groupName)
            self.accept()

        else:
            dialog = LumaErrorDialog()
            errorMsg = self.trUtf8("Could not create group.<br><br>Reason: ")
            errorMsg.append(str(exceptionObject))
            dialog.setErrorMessage(errorMsg)
            dialog.exec_loop()


###############################################################################

    def checkLocation(self):
        if self.currentPage() == None:
            return 1

        if (self.locationServer == None) or (self.locationDN == None):
            return 0
        else:
            return 1

###############################################################################


    def checkNext(self):
        result = self.checkLocation()

        if result == 0:
            tmpDialog = QMessageBox(self.trUtf8("Warning: Location"),
                self.trUtf8("""Please select a location where to store the group."""),
                QMessageBox.Critical,
                QMessageBox.Ok,
                QMessageBox.NoButton,
                QMessageBox.NoButton,
                self)

            tmpDialog.setIconPixmap(QPixmap(os.path.join(self.iconPath, "warning_big.png")))
            tmpDialog.exec_loop()

        elif result ==1:
            dataObject = SmartDataObject(('', {'objectClass': self.getPossibleClasses()}), self.serverMeta)
            self.accountWidget.dataObject = dataObject
            # Might be best to always fetch the current list of usedUserIDs.
            # Methods of how to handle/generate new unused uidNumbers:
            # 1: WebService
            # 2: LDAP-object to store a sequence-like object.
            # 3: The code below.. really ugly - but it works
            if not hasattr(self.accountWidget,'usedGroupIDs'):
                self.usedGroupIDs = self.retrieveGroupIDs()
            usedGroupIDs = self.groupIDs
            usedGroupIDs.sort()
            if len(usedGroupIDs) == 0:
                nextfreegid = '1024'
            else:
                tmp = usedUserIDs[len(usedUserIDs)-1] + 1
                nextfreeuid = str(tmp)
            #self.accountWidget.usedGroupIDs.append(nextfreeuid) # for performance-reasons
            dataObject.addAttributeValue('gidNumber',nextfreegid)

            self.accountWidget.initView(dataObject)

            self.next()
        
###############################################################################

    def updateLocation(self, dataObject):
        self.locationServer = dataObject.getServerMeta().name
        self.serverMeta = dataObject.getServerMeta()
        self.locationDN = dataObject.getPrettyDN()
        tmpString = self.locationDN + "@" + self.locationServer
        self.locationEdit.setText(tmpString)

###############################################################################

    def checkCN(self):
        cn = unicode(self.accountWidget.uidEdit.text())
        if len(cn) > 0:
            self.accountWidget.dataObject.addAttributeValue('cn', [cn], True)
        return

###############################################################################
    def getPossibleClasses(self):
        objectClassList = ["top", "posixGroup","groupOfNames","groupOfUniqueNames"]
        metaInfo = ObjectClassAttributeInfo(self.serverMeta)
        self.availableClasses = []
        for x in objectClassList:
            if metaInfo.hasObjectClass(x):
                self.availableClasses.append(x)
        return self.availableClasses

###############################################################################
