'''
Created on Jul 14, 2014

@author: mandy
'''
from PyQt4.QtGui import QGraphicsItem, QGraphicsEllipseItem, QColor, QBrush, QPen, QPainter, QFont
from PyQt4.QtCore import QObject, Qt, QRectF, QRect, QPointF
import math
import MyFunctions

class UserNode(QGraphicsEllipseItem):
    '''member variables'''
    NODESIZE = 20
    NODE_BOUNDARY_SIZE = 20
    def __init__(self, username, main):
        QGraphicsEllipseItem.__init__(self)
        self.rectContent = QRectF(-0.5*self.NODESIZE, -0.5*self.NODESIZE, self.NODESIZE, self.NODESIZE)
        self.rectbound = QRectF(-0.5*self.NODE_BOUNDARY_SIZE, -0.5*self.NODE_BOUNDARY_SIZE, self.NODE_BOUNDARY_SIZE, self.NODE_BOUNDARY_SIZE)
        self.setRect(self.rectContent)
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setVisible(False)
        self.edgeList = []
        self.main = main
        self.scene = main.scene
        self.name = username
        self.roleNode = None
        self.angle2Rolenode = 0
        self.highlighted = False
        self.color = QColor(255,215,0)
        self.penColor = QColor(233, 171, 23)
        self.labelColor = QColor(125.0, 107, 0.0)
        self.font = QFont("Calibri")
        self.font.setPixelSize(self.main.FONT_SIZE)
        self.inheritHighlight = False
        self.boderColor = Qt.red
        self.inheritColor = Qt.darkBlue
        self.pen = QPen(self.boderColor)
        self.pen.setWidth(3.0)
        self.relativeX, self.relativeY = 0,0
        
    def paint(self, painter, option, widget=None):
        if self.main.mode == self.main.HIGHLIGHT_MODE:
            if self.highlighted:
                self.color = QColor(255,215,0)
                self.penColor = QColor(233, 171, 23)
                self.labelColor = QColor(125.0, 107, 0.0)
            else:
                self.color = Qt.gray
                self.penColor = Qt.darkGray
                self.labelColor = Qt.gray
        else:
            self.color = QColor(255,215,0)
            self.penColor = QColor(233, 171, 23)
            self.labelColor = QColor(125.0, 107, 0.0)
        '''draw border'''
        self.paintBorder(painter)
        '''draw outline'''
        self.pen = QPen(self.penColor)
        self.pen.setWidth(3.0)
        self.setPen(self.pen)
        self.setBrush(self.color)
        painter.setRenderHint(QPainter.Antialiasing, True)
        QGraphicsEllipseItem.paint(self, painter, option, widget)
        '''display name as label'''
        self.pen.setColor(self.labelColor)
        painter.setPen(self.pen)
        painter.setFont(self.font)
        self.labelRect = painter.fontMetrics().boundingRect(self.name)
        self.labelRect = QRect(self.labelRect.x(), self.labelRect.y(), self.labelRect.width()+3, self.labelRect.height())
        x, y = self.computeLabelPos() 
        self.paintLabel(painter, self.brush, x+3, y)
        
    def paintBorder(self, painter):
        if self in self.main.clickedRelatedNodes or self == self.main.clickedNode:
            if self.inheritHighlight:
                self.pen.setColor(self.inheritColor)
            else:
                self.pen.setColor(self.boderColor)
            painter.setPen(self.pen)
            r = self.boundingRect()
            painter.drawRect(QRect(r.x()-0.12*r.width(), r.y()-0.12*r.height(), 1.2*r.width(), 1.2*r.height()))
   
    def computeLabelPos(self):
        if self.angle2Rolenode >= 0 and self.angle2Rolenode < math.radians(90):
            x = int(self.rect().bottomRight().x())
            y = int(self.rect().bottomRight().y()-0.5*self.labelRect.height())
        elif self.angle2Rolenode < math.radians(180):
            x = int(self.rect().bottomLeft().x()-(self.labelRect.width()))
            y = int(self.rect().bottomLeft().y()-0.5*self.labelRect.height())
        elif self.angle2Rolenode < math.radians(270):
            x = int(self.rect().topLeft().x()-(self.labelRect.width()))
            y = int(self.rect().topLeft().y()-0.5*self.labelRect.height())
        else:
            x = int(self.rect().topRight().x())
            y = int(self.rect().topRight().y()-0.5*self.labelRect.height())
        return x, y
    
    def paintLabel(self, painter, oldbrush, x, y):
        rect = self.labelRect
        rect.moveTo(x, y)
        painter.drawText(rect, Qt.AlignLeft, self.name)
        
    def highlightDirNodes(self):
        for d in self.main.dirNodes:
            d.highlighted = False
            for r in d.roleNodes:
                if r.highlighted:
                    d.highlighted = True
                    break
    
    def toggleRoleNode(self):
        if self.roleNode:
            self.roleNode.highlighted = self.highlighted
            self.roleNode.toggleUserNodes()
                               
#     def highlightParentNodes(self):
#         if self.main.highlightmode == self.main.HIGHLIGHT_HIER_MODE:
#             for r in self.roleNode.allParentNodes:
#                 if r not in self.main.clickedRelatedNodes:
#                     r.inheritHighlight = True
#                     r.highlighted = True
#                     MyFunctions.addItemToList(r, self.main.clickedRelatedNodes)
#                 for d in r.dirNodes:
#                     if d not in self.main.clickedRelatedNodes:
#                         d.inheritHighlight = True
#                         MyFunctions.addItemToList(d, self.main.clickedRelatedNodes)
#                         d.highlighted = True
#                 for u in r.userNodes:
#                     if u not in self.main.clickedRelatedNodes:
#                         u.inheritHighlight = True
#                         MyFunctions.addItemToList(u, self.main.clickedRelatedNodes)
#                         u.highlighted = True
                                          
    def mousePressEvent(self, event):
        if self.main.nodeMove and self.isSelected:
            for item in self.main.userNodes:
                if item != self:
                    item.setSelected(False)
            for item in self.main.roleCompactNodes:
                    item.setSelected(False)
        if event.button() == Qt.LeftButton and (not self.main.nodeMove): 
            for d in self.main.dirNodes:
                d.highlighted = False
                d.recursive = False
            self.main.mode = self.main.HIGHLIGHT_MODE
            self.main.toolBox.ui.noRHierRBtn.setEnabled(False)
            self.main.toolBox.ui.noRHierRBtn.setChecked(False)
            self.main.toolBox.ui.withRHierRBtn.setEnabled(False)
            self.main.toolBox.ui.withRHierRBtn.setChecked(True)
            self.main.toolBox.ui.roleHighlightSchemeGroupBox.setEnabled(False)
            self.main.toolBox.ui.roleChildHighlightRBtn.setChecked(True)
            QGraphicsEllipseItem.mousePressEvent(self, event)
            self.main.initiateItemsHightlightState()
            if self.main.mode == self.main.HIGHLIGHT_MODE and self.main.allowUsernodeHighlight:
                if self.highlighted:
                    '''highlight with border'''
                    if self.main.clickedNode and (self.main.clickedNode == self or self.main.clickedNode not in self.main.userNodes):
                        self.highlighted = False
                        self.main.clickedNode = None
                        self.main.clickedRelatedNodes = []
                        if self.roleNode:
                            self.roleNode.highlighted = False
                    else:
                        '''highlight with no border'''
                        self.main.policyManager.highlightNodeWithBorderUserNode(self)
                else:
                    self.main.policyManager.highlightNodeWithBorderUserNode(self)
                self.highlightDirNodes()
                self.main.policyManager.setUnclickedNodesGrey()
                self.main.updateAllUserNodesConsiderClickRelated()
                self.main.setPermInfoInRoleHierView()
                self.main.checkMainMode()
            '''Collect user operation data'''
            if self.highlighted:
                message = "HView: User("+ self.name+ "): Clicked: Apply highlighting\n"
            else:
                message = "HView: User("+ self.name+ "): Clicked: Remove highlighting\n"
            self.main.writeToFile(self.main.logFile, self.main.getCurrentTimeString()+message)
            
            if self.main.specDialog.isVisible():
                self.main.specDialog.reGenerateSpec()
            self.main.updateAllScenes()
            self.main.showHintContent()