#coding:utf-8
'''
Created on Oct 14, 2014
@author: root
'''

import json

from PyQt4.QtCore import Qt, SIGNAL, QRegExp
from PyQt4.QtGui import QVBoxLayout, QLabel, QComboBox, QGridLayout, QRegExpValidator, QLineEdit, QPushButton, \
    QHBoxLayout

from base.infohintdialog import InfoHintDialog
from base.storeinfoparser import StoreInfoParser
from setting.centerapi import CenterApi
from setting.getnetinfo import NetCtl
import setting.globalfunc


class CenterEditDialog(InfoHintDialog):
    def __init__(self, hintInfo="", parent = None):
        InfoHintDialog.__init__(self, hintInfo, parent)
        self.setStyleSheet("QWidget{font-size : 10pt;}"
                           "QLineEdit{border:1px groove rgb(170,214,252);}"
                           "QLineEdit{height:25;}"
                           "QComboBox{border: 1px groove rgb(170,214,252);}"
                           "QComboBox{height:25;}"
                           "QComboBox::drop-down{border-bottom-right-radius: 3px;}"
                           "QComboBox::drop-down{subcontrol-origin: padding;}"
                           "QComboBox::drop-down{subcontrol-position: top right;}"
                           "QComboBox::drop-down{width: 20px;}"
                           "QComboBox::drop-down{border-left-width: 1px;}"
                           "QComboBox::drop-down{border-left-color: rgb(170,214,252);}"
                           "QComboBox::drop-down{border-left-style: solid;}"
                           "QComboBox::drop-down{border-top-right-radius: 3px;}"
                           "QComboBox::down-arrow {image:url(../images/s2_r8_c10.gif);}"
                           "QPushButton{background:url(../images/button.png);border:2px;}")
        self.setWindowFlags(Qt.Dialog|Qt.WindowStaysOnTopHint|Qt.FramelessWindowHint)
        self.setWindowModality(Qt.ApplicationModal)
        self.setFixedSize(400,350)
        self.hintInfoDialog = InfoHintDialog()
        self.netCtl = NetCtl()
        self.centerApi = CenterApi()
        self.labelName = QLabel(u"平台:")
        
        self.lineEditName = QLineEdit()
        
        self.labelIp = QLabel(u"IP地址：")
        self.lineEditIp = QLineEdit()
        
        rx = QRegExp("^([1]?/d/d?|2[0-4]/d|25[0-5])/.([1]?/d/d?|2[0-4]/d|25[0-5])/.([1]?/d/d?|2[0-4]/d|25[0-5])/.([1]?/d/d?|2[0-4]/d|25[0-5])$")
        validator = QRegExpValidator(rx,self)
        self.lineEditIp = QLineEdit()
        self.lineEditIp.setValidator(validator)
        self.lineEditIp.setInputMask("000.000.000.000;")
        self.lineEditIp.setEnabled(False)
        
        self.labelPort = QLabel(u"端口号：")
        self.labelNet = QLabel(u"网络：")
        self.lineEditPort = QLineEdit()
        self.lineEditPort.setEnabled(False)
        self.comboNet = QComboBox()
        
        self.saveBtn = QPushButton(u'保存')
        self.saveBtn.setFixedSize(75,27)
        self.saveBtn.setFlat(True)
        self.cancelBtn = QPushButton(u'取消')
        self.cancelBtn.setFixedSize(75,27)
        self.cancelBtn.setFlat(True)
        
        miniLayout = QGridLayout()
       
        miniLayout.addWidget(self.labelName,0,0)
        miniLayout.addWidget(self.lineEditName,0,1)
        miniLayout.addWidget(self.labelIp,1,0)
        miniLayout.addWidget(self.lineEditIp,1,1)
        miniLayout.addWidget(self.labelPort,2,0)
        miniLayout.addWidget(self.lineEditPort,2,1)
        miniLayout.addWidget(self.labelNet,3,0)
        miniLayout.addWidget(self.comboNet,3,1)
        
        btnLayout = QHBoxLayout()
        btnLayout.addWidget(self.saveBtn)
        btnLayout.addSpacing(50)
        btnLayout.addWidget(self.cancelBtn)
        
        vLayout = QVBoxLayout()
        vLayout.addSpacing(60)
        vLayout.addLayout(miniLayout)
        vLayout.addSpacing(30)
        vLayout.addLayout(btnLayout)
        
        self.mainlayout = QHBoxLayout(self)
        self.mainlayout.addSpacing(70)
        self.mainlayout.addLayout(vLayout)
        self.mainlayout.addSpacing(70)
        
        
        
        self.okBtn.hide()
        
        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)
        self.connect(self.cancelBtn, SIGNAL("clicked()"),self.slotCancel)
        
    
    def setCenterInfo(self,info):
        self.centerInfo = info
        self.refreshInfo()
    def refreshInfo(self):
        info = self.centerInfo
        self.lineEditName.setText(info["netName"])
        self.lineEditIp.setText(info["netIp"])
        self.lineEditPort.setText(info["netPort"])
        
        self.comboNet.clear()
        #读取网络地址信息
     
        netAddressList = self.netCtl.getNetAddressList()
        num = len(netAddressList)
    
        index = 0
        
        for i in range(num):
            netName = netAddressList[i]["netName"]
            if (netName == info["netLocal"]):
                index = i
            netId = netAddressList[i]["addressID"]
            self.comboNet.addItem(netName)
            self.comboNet.setItemData(i, netId, Qt.UserRole + 1)
        self.comboNet.setCurrentIndex(index)
    
    def slotSave(self):
        
        name = self.lineEditName.text().trimmed()
        ip = self.lineEditIp.text().trimmed()
        net = self.comboNet.currentText()

        if name == "":

            self.hintInfoDialog.setHintInfo(u"平台不能为空!")
            self.hintInfoDialog.show()
            self.hintInfoDialog.move(setting.globalfunc.moveToCenter(self.hintInfoDialog.width(), self.hintInfoDialog.height()))
            self.close()
           
            return 

        centerList0 = StoreInfoParser.instance().getNetworkSwitch()
        centerList = json.loads(centerList0)

        i = 0

        for item in centerList:

            subListName = item.split(":")[0]
            subListIp = item.split(":")[1]
            subListPort = item.split(":")[2]
            subListssl = item.split(":")[3]
            subListcaName = item.split(":")[4]
            subListID = item.split(":")[5]
            subListNet = item.split(":")[6]
            subListSwitch = item.split(":")[7]
          
            if subListIp == ip:
                
                centerList.remove(item)
                content = unicode(name, "utf-8") + ":" + subListIp + ":" + subListPort + ":" + subListssl + ":" + subListcaName + ":" + subListID + ":" + net + ":" + subListSwitch
                centerList.append(str(content))

        StoreInfoParser.instance().setNetworkSwitch(json.dumps(centerList, ensure_ascii=False))
        
        self.hintInfoDialog.setHintInfo(u"编辑平台成功")
        self.hintInfoDialog.show()
        self.hintInfoDialog.move(setting.globalfunc.moveToCenter(self.hintInfoDialog.width(), self.hintInfoDialog.height()))
        self.close()
        self.emit(SIGNAL("editupdatecenter"))
          
        
    def toList(self,listStr):
        listT = []
        listS = "a"
        if(type(listStr) == type(listS)):
            if (listStr == "[]" or listStr == "None" or listStr == ""):
                return []
            else:
                listList = []
                list = listStr.split(",")
             
                for i in range(len(list)):
                    listList.append(list[i].split("'")[1])
                return listList
            
        elif(type(listStr) == type(listT)):
            return listStr  
        return []      
    def slotCancel(self):
        self.close()
