#coding=utf-8
from PyQt4.QtGui import QMainWindow, QTableWidgetItem, QDialog, QWidget, QHBoxLayout, QPushButton
from PyQt4.QtCore import Qt, SIGNAL, QPoint, QString
from view.desktop.vmwindowview import Ui_MainWindow
from common.globalfun import moveWidgetToScreenCenter
from common.infohintdialog import InfoHintDialog
import threading
from passwordeditdialog import PasswordEditDialog
from controller.desktop.menuwidget import CustomMenuWidget
from common.messagebox import MessageBox
from common.commondata import actionHintInfo, vmStatusMap
from model.request.utilityrequestoperationwrap import UtilityRequestOperationWrap
from controller.setting.setting import Setting
from controller.setting.passworddialog import PasswordDialog
 
class VMMainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        super(VMMainWindow,self).__init__(parent)
        #--------------界面初始化-top
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setMouseTracking(True)
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.initTableHeader()
        
        self.initVariable()
        
        self.bandSignalSlot()
        
        #虚拟机主窗口移动到屏幕中心
        moveWidgetToScreenCenter(self, checkMulMonitor=False)
        
        
    def initVariable(self):
        self.currentVMId = ""
        self.customMenu = CustomMenuWidget()
        self.customMenu.setObjectName("customMenu")
        
    def bandSignalSlot(self):
        self.connect(self.pushButtonUpdate, SIGNAL("clicked()"),self.slotRefreshVMList)
        self.connect(self, SIGNAL("actionSuccess"),self.slotRefreshVMList)
        self.connect(self.pushButtonSet, SIGNAL("clicked()"),self.slotSetting)
        self.connect(self.pushButtonLogout, SIGNAL("clicked()"),self.slotLogout)
        self.connect(self.pushButtonChangePassword, SIGNAL("clicked()"),self.slotchangePassword)
        self.connect(self, SIGNAL("freshSuccess"),self.updateVMList)
        self.connect(self.customMenu, SIGNAL("menuAction"),self.slotExecMenuAction)
        self.connect(self, SIGNAL("ConnectionError"),self.slotPopHintInfo)
        self.connect(self, SIGNAL("actionFailed"),self.slotPopHintInfo)
        
        
    def initTableHeader(self):
        self.tableWidget.clear()
        self.tableWidget.setColumnCount(8)
        labelList = [u"项目", u"云主机名称", u"配置", u"内存", u"虚拟内核", u"硬盘", u"状态", u"操作"]
        self.tableWidget.setHorizontalHeaderLabels(labelList)
        
        self.tableWidget.setColumnWidth(0,106)
        self.tableWidget.setColumnWidth(1,150)
        self.tableWidget.setColumnWidth(2,150)
        self.tableWidget.setColumnWidth(3,100)
        self.tableWidget.setColumnWidth(4,105)
        
        self.tableWidget.hideColumn(0)
        self.tableWidget.hideColumn(2)
        
        
    def slotPopHintInfo(self, info):
        if info == "ConnectionError":
            InfoHintDialog(u'操作失败，请查看网络连接是否正常！').exec_()
        elif info == "shutDown":
            InfoHintDialog(u'执行关闭云主机操作失败！').exec_()
        elif info == "start":
            InfoHintDialog(u'执行打开云主机操作失败！').exec_()
        elif info == "reboot":
            InfoHintDialog(u'执行重启云主机操作失败！').exec_()
        else:
            InfoHintDialog(info).exec_()
        
    def slotRefreshVMList(self):
        def getHttpRequest():   
            utility = UtilityRequestOperationWrap()
            vmBaseInfoList = utility.getVMListInfo()
            if vmBaseInfoList == None or vmBaseInfoList == "ConnectionError":
                return
             
            self.emit(SIGNAL("freshSuccess"), vmBaseInfoList)
        
        self.initTableHeader()
        tContext = threading.Thread(target=getHttpRequest)
        tContext.start()
        
    def slotSetting(self):
        passwordDialog = PasswordDialog()
        if passwordDialog.exec_() == QDialog.Accepted:
            setWidget = Setting()
            self.connect(setWidget, SIGNAL("setscreenover"), self.adjustPosition)
            setWidget.exec_()
            
    def adjustPosition(self):
        self.emit(SIGNAL("moveWidgetToScreenCenter"))
        
    def slotLogout(self):
        self.emit(SIGNAL("logout"))
    
    def slotchangePassword(self):
        passEDlg = PasswordEditDialog()
        passEDlg.exec_()        
        
    def updateVMList(self, vmBaseInfoList):
        self.customMenu.setActionStatus(True)
        self.tableWidget.setRowCount(len(vmBaseInfoList))
        for row, vmBaseInfo in enumerate(vmBaseInfoList):
            projectNameItem = QTableWidgetItem(vmBaseInfo.projectName)
            projectNameItem.setTextAlignment(Qt.AlignCenter)
            projectNameItem.setToolTip(vmBaseInfo.projectName)
            projectNameItem.setData(Qt.UserRole, vmBaseInfo.id) 
            projectNameItem.setData(Qt.UserRole + 1, vmBaseInfo.tenantId)
            self.tableWidget.setItem(row, 0, projectNameItem)
            
            chostNameItem = QTableWidgetItem(vmBaseInfo.chostName)
            chostNameItem.setTextAlignment(Qt.AlignCenter)
            chostNameItem.setToolTip(vmBaseInfo.chostName)
            self.tableWidget.setItem(row, 1, chostNameItem)
            
            configNameItem = QTableWidgetItem(vmBaseInfo.configName)
            configNameItem.setTextAlignment(Qt.AlignCenter)
            configNameItem.setToolTip(vmBaseInfo.configName)
            configNameItem.setData(Qt.UserRole, vmBaseInfo.flavorId)
            configNameItem.setData(Qt.UserRole + 1, vmBaseInfo.tenantId)
            configNameItem.setData(Qt.UserRole + 2, vmBaseInfo.projectName)
            self.tableWidget.setItem(row, 2, configNameItem)
            
            ramItem = QTableWidgetItem(str("%sMB" % vmBaseInfo.ram))
            ramItem.setTextAlignment(Qt.AlignCenter)
            ramItem.setToolTip(str("%sMB" % vmBaseInfo.ram))
            self.tableWidget.setItem(row, 3, ramItem)
            
            vcpusItem = QTableWidgetItem(str(vmBaseInfo.vcpus))
            vcpusItem.setTextAlignment(Qt.AlignCenter)
            vcpusItem.setToolTip(str(vmBaseInfo.vcpus))
            self.tableWidget.setItem(row, 4, vcpusItem)
            
            diskItem = QTableWidgetItem(str("%sGB" % vmBaseInfo.disk))
            diskItem.setTextAlignment(Qt.AlignCenter)
            diskItem.setToolTip(str("%sGB" % vmBaseInfo.disk))
            self.tableWidget.setItem(row, 5, diskItem)
            
            statusItem = QTableWidgetItem(vmStatusMap.get(vmBaseInfo.status, ""))
            statusItem.setTextAlignment(Qt.AlignCenter)
            statusItem.setToolTip(vmStatusMap.get(vmBaseInfo.status, ""))
            self.tableWidget.setItem(row, 6, statusItem)
            self.customMenu.setRebootActionStatus(vmBaseInfo.status != "reboot")
            
            self.tableWidget.setCellWidget(row, 7, self.getCellWidget(vmBaseInfo.status))
            
        
    def getCellWidget(self, chostStatus):
        cellWidgt = QWidget()
        hLayout = QHBoxLayout()
        
        buttonWidth = 90
        buttonHeight = 25
        
        startBtn = QPushButton()
        startBtn.setObjectName("butStart")
        text = u"进入云桌面" if chostStatus == "ACTIVE" else u"启动云桌面"
        startBtn.setText(text)
        btnWidth = buttonWidth - 5 if chostStatus == "ACTIVE" else buttonWidth + 14
        startBtn.setFixedSize(btnWidth, buttonHeight)
        
        self.connect(startBtn, SIGNAL("clicked()"), self.startVm)
#         
        menuButton = QPushButton()
        menuButton.setObjectName("butMenu")
        menuButton.setFixedSize(buttonHeight - 7, buttonHeight)
        self.connect(menuButton, SIGNAL("clicked()"), self.showMenu)
            
        hLayout.setSpacing(0)
        hLayout.setMargin(0)
        hLayout.addStretch()
        hLayout.addWidget(startBtn)
        if chostStatus == "ACTIVE":
            hLayout.addWidget(menuButton)
        hLayout.addStretch()
    
        cellWidgt.setLayout(hLayout)
        
        return cellWidgt
            
    def showFlavorDetail(self, pos):
        point = self.tableWidget.mapFromParent(pos)
        headerWidth = self.tableWidget.verticalHeader().width()
        headerHeight = self.tableWidget.horizontalHeader().height()
        index = self.tableWidget.indexAt(QPoint(point.x() - headerWidth, point.y() - headerHeight))
        if index.row() >= 0 and index.column() == 2:
            subItem = self.tableWidget.item(index.row(), index.column())
            if not subItem:
                return
            
            flavorId = str(subItem.data(Qt.UserRole).toString())
            tenantId = str(subItem.data(Qt.UserRole + 1).toString())
            tenantName = str(subItem.data(Qt.UserRole + 2).toString())
            if not subItem.text():
                return
            
            utility = UtilityRequestOperationWrap()
            flavorInfo = utility.getFlavorDetailInfo(tenantName, tenantId, flavorId)
            if flavorInfo == None or flavorInfo == "ConnectionError":
                return
            subItem.setToolTip(u"内存: %sMB\n虚拟内核: %s\n硬盘: %sGB" % (flavorInfo.ram, flavorInfo.vcpus, flavorInfo.disk))
            
            
    def getPopMenuPoint(self):
        pbt = QWidget().sender().parent()
        pos = QPoint(pbt.frameGeometry().x(), pbt.frameGeometry().y())
        index = self.tableWidget.indexAt(QPoint(pbt.frameGeometry().x(), pbt.frameGeometry().y()))
        self.setCurrentVMInfo(index)
        
        buttonWidth = 90
        buttonHeight = 25
        x = pos.x() + pbt.width() - (pbt.width() - buttonWidth - buttonHeight) / 2 + 20
        y = 90 + 30 + pos.y()
        
        return QPoint(self.pos().x() + x, self.pos().y() + y)
            
    def showMenu(self):
        self.customMenu.move(self.getPopMenuPoint())
        self.customMenu.show()
        
#         menu = self.customMenu.createOnMenu()
#         menu.move(self.getPopMenuPoint())
#         menu.show()
    
    def getSelectTableItemIndex(self):
        pbt = QWidget().sender().parent()
        index = self.tableWidget.indexAt(QPoint(pbt.frameGeometry().x(), pbt.frameGeometry().y()))
        return index
    
    def setCurrentVMInfo(self, index):
        subItem = self.tableWidget.item(index.row(), 0)
        self.currentVMId = str(subItem.data(Qt.UserRole).toString())
        self.currentTenantId = str(subItem.data(Qt.UserRole + 1).toString())
        self.currentTenantName = str(subItem.text())
        self.currentClickIndex = index
        
    def startVm(self):
        startBtn = self.sender()
        preText = startBtn.text()
        startBtn.setText(u"连接中,.")
        index = self.getSelectTableItemIndex()
        self.setCurrentVMInfo(index)
        
        #判断虚拟机是否已经启动
        def execOpenVM():
            utility = UtilityRequestOperationWrap()
            value = utility.openVM(self.currentVMId, self.currentTenantName, self.currentTenantId)
            if value is not True:
                self.emit(SIGNAL("actionFailed"), value)
                startBtn.setText(preText)
            else:
                self.emit(SIGNAL("actionSuccess"))
            
        tContext = threading.Thread(target=execOpenVM)
        tContext.start()
        
    def slotExecMenuAction(self, action):
        
        if MessageBox(actionHintInfo.get(action, u"是否执行该操作？")).exec_() != QDialog.Accepted:
            return
        
        def execAction(action):    
            utility = UtilityRequestOperationWrap()
            isOk = utility.execVMAction(action, self.currentVMId, self.currentTenantName, self.currentTenantId)
            if isOk is True:
                self.customMenu.setActionStatus(False)
                if action == "shutDown":
                    subItem = self.tableWidget.item(self.currentClickIndex.row(), 6)
                    subItem.setText(u"正在关机")
#                 else:
#                     self.emit(SIGNAL("actionSuccess"))
                
                utility.checkVMStatus(action, self.currentVMId, self.currentTenantName, self.currentTenantId)
                self.emit(SIGNAL("actionSuccess"))
            else:
                self.emit(SIGNAL("actionFailed"), action)
        
        tContext = threading.Thread(target=execAction, args=(action,))
        tContext.start()
        
    
        
        