'''
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 Feb 5, 2012

@author: yifli
'''

from PyQt4.QtGui import QUndoCommand
from PyQt4.QtCore import QRectF
from FileNode import FileNode
from TypeNode import TypeNode
from EdgeItem import EdgeItem
from RadialTreeLayout import RadialTreeLayout
import string

class AddFileNodeCommand(QUndoCommand):
    def __init__(self, parentItem, name, typeName, flag):
        QUndoCommand.__init__(self)
        self.parentItem = parentItem
        self.scene = self.parentItem.scene()
        self.name = name
        self.typeName = typeName
        self.flag = flag
        
    def undo(self):
        self.parentItem.children.remove(self.node)
        self.parentItem.edgeList.remove(self.edge)
        self.scene.removeItem(self.edge)
        self.scene.removeItem(self.node)
        self.scene.update()
    
    def redo(self):
        # find the type node this file assigned to
        for item in self.scene.items():
            if isinstance(item, TypeNode):
                if item.name == self.typeName:
                    type = item
                    break
        
        # create the file node and the associated edge in type graph    
        self.node = FileNode(self.name, type, self.flag)
        self.node.inheritFromNode = None
        self.node.fullPath = self.parentItem.fullPath+'/'+self.name
        self.edge = EdgeItem(EdgeItem.FILE_CONN, self.parentItem, self.node)
        self.node.edgeList.append(self.edge)
        self.parentItem.edgeList.append(self.edge)
        self.parentItem.children.append(self.node)
        self.node.parent = self.parentItem
        self.scene.addItem(self.node)
        self.scene.addItem(self.edge)
        layout = RadialTreeLayout(self.scene)
        layout.buildTreeTable(self.scene.typeGraphRoot)
        layout.layout()
        layout.mapToScene()
        
        # update information about type graph
        level = len(string.split(self.node.fullPath, '/'))
        if level not in self.scene.typeGraph:
            width = self.scene.views()[0].viewport().width()
            height = self.scene.views()[0].viewport().height()
            d = min(width, height) / 2.0  / len(self.scene.typeGraph)
            radius = d * level
            rootX = self.scene.typeGraphRoot.pos().x()
            rootY = self.scene.typeGraphRoot.pos().y()
            self.scene.typeGraph[level] = [[self.node], QRectF(rootX-radius, rootY-radius, 2*radius, 2*radius)]
        else:
            self.scene.typeGraph[level][0].append(self.node)
        
        self.parentItem.scene().update()
