'''
Created on Nov 3, 2014

@author: Mandy
'''
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from MainWindow import MainWindow
from DomainNode import DomainNode
import re

class DTEForCommandLine(object):

    def __init__(self):
        self.app = None
        if self.app is None:
            self.app= self.startVisualizationWindow()
#         self.importPolicy('/Users/manwang/Documents/workspace/DTEvisual/src/policies/hwexample.dte')
#         self.initVisualizationForQuery('/Users/manwang/Documents/workspace/DTEvisual/src/policies/hwexample.dte', 0, ['/usr/bin/sh/gppd'])
            
    def UIConfiForQuery(self, questionId, paras):
        self.main.queryWindowDockWidget.show()
        self.main.queryWindow.setQueryForQuestion(questionId)
        self.main.queryWindow.getQueryResultFromCommandLineInput(questionId, paras)
        self.main.currentAction = self.main.ui.actionGeneral_Graph
        self.main.viewModeChanged(self.main.currentAction)
        
    def startVisualizationWindow(self):
        app = QApplication(sys.argv)
        QCoreApplication.setApplicationName('DTEvisual')
        QCoreApplication.setApplicationVersion('1.0')
        
        QApplication.setStyle('plastique')
        app.setStyleSheet("""QToolTip {
                            background-color:white;
                            color:black;
        }""")
        self.main = MainWindow()
        return app
    
    def initVisualizationForQuery(self, filename, questionId, paras = []):
        #paras is a list containing the input for query interface
        self.main.show()
        self.main.importSpec(filename)#need changes to avoid repeated reloads
        self.UIConfiForQuery(questionId, paras)
        exitcode = self.app.exec_()
        sys.exit(exitcode)
        self.app = None
    
    def importPolicy(self, filename):
        self.main.importSpec(filename)
        self.queryManager('none','login_d', '/usr/bin/sh', set('x'))
                
    def queryManager(self, subjname, domainname, objname, permissions):
        noneinput = re.compile('none', re.IGNORECASE)
        if re.match(noneinput, subjname):
            self.queryDomainAccessObj(domainname, objname, permissions)
#         elif re.match(noneinput, rolename):
#             self.queryUserAccessObj(username, objname)
#         else:
#             self.queryUserAccessObjFromRole(username, rolename, objname)
        
    def queryDomainAccessObj(self, domainname, objname, permissions):
        '''add explanation for no access'''
        answer = None
        output = ''
        domainNode = None
        for d in self.main.scene.items():
            if isinstance(d, DomainNode):
                if d.name == domainname:
                    domainNode = d
        typeNode = self.main.queryWindow.findFileType(objname)
        if domainNode == None:
            output='Domain (%s) does not exist in the policy.\n' %(domainname)
            answer = False
        elif typeNode == None:
            output='The object (%s) is not assigned to any type. Therefore, domain (%s) does not have access to it.\n' % (objname, domainname)
            answer = False
        else:
            for e in domainNode.edgeList:
                descrip = e.description.replace(' ', '')
                index = descrip.find('{')
                if index!=-1:
                    second = descrip[index+1:descrip.rfind('}')].split(',')
                    first = descrip[:descrip.find('{')]
                    descrip = set()
                    for s in second:
                        descrip.add(first+s)
                if e.endItem == typeNode.type:
                    perms = set(descrip)
                    if permissions.issubset(perms):
                        answer = True
                        output = 'Domain (%s) has %s access to the object (%s).\n' % (domainname, descrip, objname)
                    else:
                        answer = False
                        diff = permissions - perms
                        output = 'Domain (%s) does not have %s access to the object (%s)' % (domainname, ''.join(diff), objname)
                if permissions == set('x') and objname.strip(' ') in descrip:
                    answer = True
                    output = 'Domain (%s) has x access to the object (%s) since the object is an entry point from this domain to another domain.\n' % (domainname, objname)
        return answer, output
        