'''
Accessible Access Control 1.0
2012-2104 Michigan Technological University
Supported in part by NSF grants: DUE-1140512, DUE-1245310 and IIS-1319363
Developer: Man Wang
Advisors:Dr. Steve Carr, Dr. Jean Mayo, Dr. Ching-Kuang Shene and Dr. Chaoli Wang
'''
'''
Created on 2013-02-07

@author: mandy
'''
from PyQt4.QtGui import QDialog
from PyQt4.QtCore import Qt
from Ui_SpecDialog import Ui_Dialog
import re

class SpecDialog(QDialog):
    def __init__(self, scene):
        QDialog.__init__(self)
        self.scene = scene
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.setLayout(self.ui.verticalLayout)
        #self.ui.errorLabel.setWordWrap(True)
        flags = Qt.Dialog | Qt.WindowStaysOnTopHint
        self.setWindowFlags(flags)
        self.ui.generatePushButton.clicked.connect(self.reGenerateSpec)
        self.ui.closePushButton.clicked.connect(self.hide)
        
    def updateUserAssign(self, prevcnode, cnode, username):
        found = False
        prevcname = prevcnode.clearance+':'+':'.join(prevcnode.category)
        cname = cnode.clearance+':'+':'.join(cnode.category)
        lines = self.scene.usrAssign.split('\n')
        assignment = []
        p = re.compile('^\s*\n\s*$')
        for e in lines:
            if e=='\n':
                lines.remove(e)
            if e.find(prevcname)!=-1:
                users = set()
                for u in prevcnode.userNodes:
                    users.add(u.name)
                e = 'users\t'+prevcname+'\t'+','.join(users)
            elif e.find(cname)!=-1:
                users = set()
                for u in cnode.userNodes:
                    users.add(u.name)
                    e = 'users\t'+cname+'\t'+','.join(users)
                found = True
            elif not p.match(e):
                assignment.append(e)
        if found is False:
            users = set()
            for u in cnode.userNodes:
                users.add(u.name)
            assignment.append('\nusers\t'+cname+'\t'+','.join(users))
        self.scene.usrAssign = '\n'.join(assignment)
        self.scene.spec = self.scene.securitySpec+'\n'+self.scene.typeAssign+'\n'+self.scene.usrAssign
        
    def reGenerateSpec(self):    
        self.scene.spec = self.scene.securitySpec+'\n'+self.scene.typeAssign+'\n'+self.scene.usrAssign
        self.ui.specTextEdit.clear()
        self.ui.specTextEdit.setPlainText(self.scene.spec)