'''
Created on Jun 9, 2014

@author: mandy
'''
from PyQt4.QtGui import QDialog, QColor
from PyQt4.QtCore import Qt, QString
from Ui_SpecDialog import Ui_Dialog
from RoleNode import RoleNode, RoleCompactNode
from UserNode import UserNode
from DirNode import DirNode

class SpecDialog(QDialog):
    
    def __init__(self, main):
        QDialog.__init__(self)
        self.main = main
        self.prevInheritanceSet = set()
        self.prevUserSet = set()
        self.prevObjSet = set()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.setLayout(self.ui.verticalLayout)
        flags = Qt.Dialog | Qt.WindowStaysOnTopHint
        self.setWindowFlags(flags)
        self.ui.generatePushButton.clicked.connect(self.reGenerateSpec)
        self.ui.closePushButton.clicked.connect(self.closeWindow)

    def closeEvent(self, evt):
        self.main.writeToFile(self.main.logFile, self.main.getCurrentTimeString()+\
                                    "Specification Window off\n")
        evt.accept()
        
    def closeWindow(self):
        self.hide()
        self.main.hintForSpecWindow()
        self.main.writeToFile(self.main.logFile, self.main.getCurrentTimeString()+\
                                    "Specification Window off\n")
                
    def getHighlightedNodes(self, rolenodes, dirnodes, usernodes):
        if isinstance(self.main.clickedNode, RoleCompactNode) or isinstance(self.main.clickedNode, RoleNode):
            rolenodes.append(self.main.clickedNode)
        elif isinstance(self.main.clickedNode, UserNode):
            usernodes.append(self.main.clickedNode)
        elif isinstance(self.main.clickedNode, DirNode):
            dirnodes.append(self.main.clickedNode)
            
        for item in self.main.clickedRelatedNodes:
            if isinstance(item, RoleCompactNode):
                rolenodes.append(item)
            elif isinstance(item, UserNode):
                usernodes.append(item)
            elif isinstance(item, DirNode):
                dirnodes.append(item)
                
    def checkNodeWithNameInList(self, name, itemList):
        for i in itemList:
            if i.name == name:
                return True, i
        return False, None
        
    def getSpecFromVisualization(self):
        rolenodes = []
        dirnodes = []
        usernodes = []
        oneline = ''
        self.getHighlightedNodes(rolenodes, dirnodes, usernodes)
        self.ui.specTextEdit.clear()
        for r, relation in self.main.role_adjmat.iteritems():
            flag, rnode = self.checkNodeWithNameInList(r, rolenodes)
            if flag:
                if self.main.roleHighlightScheme == self.main.ROLE_HIGHLIGHT_CHILDREN or \
                    self.main.roleHighlightScheme == self.main.ROLE_HIGHLIGHT_BOTH:
                    if rnode.inheritHighlight:
                        self.ui.specTextEdit.setTextColor(QColor(0,0,255))
                    else:
                        self.ui.specTextEdit.setTextColor(QColor(255,0,0))
            childrenList = list(relation.children)
#             if childrenList == []:
#                 oneline = 'inheritance: '+r
#             else:
            oneline = ''
            if childrenList:
                oneline = 'inheritance: '+r+' > '
                for c in childrenList:
                    flag, rnode = self.checkNodeWithNameInList(c, rolenodes)
                    if flag:
                        if self.main.roleHighlightScheme == self.main.ROLE_HIGHLIGHT_PARENTS or \
                            self.main.roleHighlightScheme == self.main.ROLE_HIGHLIGHT_BOTH:
                            if rnode.inheritHighlight:
                                self.ui.specTextEdit.setTextColor(QColor(0,0,255))
                            else:
                                self.ui.specTextEdit.setTextColor(QColor(255,0,0))
                    oneline += c+', '
                oneline = oneline[:oneline.rfind(',')]
            self.ui.specTextEdit.append(QString(oneline))
            self.ui.specTextEdit.setTextColor(QColor(0,0,0))
        self.ui.specTextEdit.append(QString('\n'))
        
        for r in self.main.roleCompactNodes:
            flag, rnode = self.checkNodeWithNameInList(r.name, rolenodes)
            if flag:
                if rnode.inheritHighlight:
                    self.ui.specTextEdit.setTextColor(QColor(0,0,255))
                else:
                    self.ui.specTextEdit.setTextColor(QColor(255,0,0))
            oneline = 'user: '+r.name+' '
            if r.userNodes == []:
                continue
            else:
                for u in r.userNodes:
                    oneline += u.name+', '
                oneline = oneline[:oneline.rfind(',')]
            self.ui.specTextEdit.append(QString(oneline))
            self.ui.specTextEdit.setTextColor(QColor(0,0,0))
        self.ui.specTextEdit.append(QString('\n'))
        unoRole = False
        oneline = 'free_user: '
        for u in self.main.userNodes:
            if u.roleNode == None:
                unoRole = True
                oneline += u.name + ', '
                if u == self.main.clickedNode:
                    self.ui.specTextEdit.setTextColor(QColor(255,0,0))
        if unoRole:
            oneline = oneline[:oneline.rfind(',')]
            self.ui.specTextEdit.append(QString(oneline))
            self.ui.specTextEdit.setTextColor(QColor(0,0,0))
        self.ui.specTextEdit.append(QString('\n'))
        for r in self.main.role_res_mat.keys():
            objList, permIter, permissions, permissionStrings, completePermStringList = self.main.computeSpec.getObjPermForRole(r)
            for i in xrange(len(objList)):
                flag, rnode = self.checkNodeWithNameInList(r, rolenodes)
                if flag:
                    if rnode.inheritHighlight:                        
                        self.ui.specTextEdit.setTextColor(QColor(0,0,255))
                    else:
                        self.ui.specTextEdit.setTextColor(QColor(255, 0, 0))
                oneline = 'object: '+r+' '+permissionStrings[i]+' '+completePermStringList[0][i]
                self.ui.specTextEdit.append(QString(oneline))
                self.ui.specTextEdit.setTextColor(QColor(0,0,0))
        
    def reGenerateSpec(self):
#         inheritanceSet = set()
#         userSet = set()
#         objectSet = set()
#         currentContent = self.ui.specTextEdit.toPlainText()
#         lines = str(currentContent).split('\n')
#         for i in lines:
#             if i.find('inheritance:') != -1:
#                 inheritanceSet.add(i)
#             elif i.find('user:') != -1:
#                 userSet.add(i)
#             elif i.find('object:') != -1:
#                 objectSet.add(i)
#         if (not currentContent.isEmpty()) and \
#             self.prevInheritanceSet != inheritanceSet or self.prevObjSet != objectSet or self.prevUserSet != userSet:#self.main.spec != currentContent:
#             self.specDir = QString('./policies/temp.rbac')
#             f = open(self.specDir, "w")
#             for line in lines:
#                 if line!='\n':
#                     f.write('%s\n'% line)
#             f.close()
#             self.main.initParam()
#             self.main.importSpec(self.specDir)
#             self.main.viewModeChanged(self.main.currentAction)
        self.getSpecFromVisualization()
#         self.prevInheritanceSet = inheritanceSet
#         self.prevObjSet = objectSet
#         self.prevUserSet = userSet
        self.main.hintForSpecWindow(True)