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

@author: yifli
'''

from PyQt4.QtGui import QUndoCommand, QMessageBox
from TypeNode import TypeNode
from FileNode import FileNode

class DeleteNodeCommand(QUndoCommand):
 
    def __init__(self, item):
        QUndoCommand.__init__(self)
        self.item = item
        self.scene = self.item.scene()
        self.affectedFileNodes = []
    
    def undo(self):
        if isinstance(self.item, TypeNode):
            TypeNode.counter += 1
            for n in self.affectedFileNodes:
                n.type = self.item
        self.scene.addItem(self.item)
        if not self.scene.displayGeneralGraph:
            self.item.setVisible(False)
        for e in self.item.edgeList:
            self.scene.addItem(e)
            if not self.scene.displayGeneralGraph:
                e.setVisible(False)
        self.item.scene().update()
    
    def redo(self):
        for e in self.item.edgeList:
            self.scene.removeItem(e)
        self.scene.removeItem(self.item)

        if isinstance(self.item, TypeNode):
            TypeNode.counter -= 1
               
            for item in self.scene.items():
                if isinstance(item, FileNode):
                    if item.type is self.item:
                        self.affectedFileNodes.append(item)
                        # go up in the tree to find out if it's possible to inherit a type from its ancestors
                        inherited = False
                        parent = item.parent
                        while parent:
                            if parent.type is self.item:
                                parent = parent.parent
                            else:
                                item.type = parent.type
                                inherited = True
                                break
                        if not inherited:
                            item.type = None
                        
                        # go down in the tree to look for affected children
                        if item.flag == 2 or item.flag == 3:
                            nodes = item.children
                            while nodes:
                                node = nodes.pop(0)
                                for n in node.children:
                                    if n.inheritFromNode is self.item:
                                        n.type = None
                                        self.affectedFileNodes.append(n)
                                    if n.children:
                                        nodes.extend(n.children) 

                         
        self.scene.update()
        