#coding:utf-8
from PyQt4.QtCore import Qt, SIGNAL, QRegExp
from PyQt4.QtGui import QVBoxLayout, QLabel, QComboBox,QGridLayout, QRegExpValidator, QLineEdit, QPushButton, \
    QHBoxLayout

from common.infohintdialog import InfoHintDialog
from model.cfg.storeinfoparser import StoreInfoParser
# from setting.getnetinfo import NetCtl
# from setting.centerapi import CenterApi
# from model.cfg.storeinfoparser import StoreInfoParser
# import common.globalfun
import json

'''
Created on Oct 14, 2014
@author: root
'''

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,250)
        self.hintInfoDialog = InfoHintDialog()
        self.labelName = QLabel(u"平台:")
        self.lineEditName = QLineEdit()
        
        self.labelIp = QLabel(u"IP地址：")
        self.lineEditIp = QLineEdit()

        # ---- add for pbc on 2015.08.12 -top
        self.labelIp.setEnabled(False)
        self.lineEditIp.setEnabled(False)
        # ---- add for pbc on 2015.08.12 -end
        
        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()

        # ---- add for pbc on 2015.08.12 -top
        self.labelPort.setEnabled(False)
        self.lineEditPort.setEnabled(False)
        # ---- add for pbc on 2015.08.12 -end
        
        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)
        
        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):
        """
        change for pbc on 2015.08.12
        """
        info = self.centerInfo
        self.lineEditName.setText(info["netName"])
        self.lineEditIp.setText(info["netIp"])
        self.lineEditPort.setText(info["netSsl"])
    
    def slotSave(self):
        name = self.lineEditName.text().trimmed()
        ip = self.lineEditIp.text().trimmed()
        net = self.comboNet.currentText()
        if name == "":
            self.close()
            InfoHintDialog(u'平台不能为空 ！').exec_()
            return

        tempv=StoreInfoParser.instance().getConfigFileValue("networkswitch")
        if(tempv==""):
            return
        else:
            tempItem = {}
            tempList=json.loads(tempv)
            for item in tempList:
                if item == self.centerInfo['netName']:
                    tempItem = tempList[item] #把需要修改的项进行赋值
                    tempItem["networkName"] = str(name) #修改需要修改的key值
                    tempList.pop(item) #去掉原来的项
                    tempList[str(unicode(name, "utf-8"))] = tempItem #重新添加修改的项
                    StoreInfoParser.instance().setConfigFileValue("networkswitch",json.dumps(tempList,ensure_ascii=False))
                    self.emit(SIGNAL("editupdatecenter"))
                    self.close()
                    InfoHintDialog(u'编辑成功 ！').exec_()
                    return

        
    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()


"""
app = QApplication(sys.argv)
c = CenterEditDialog()
c.show()

app.exec_()
"""