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

# from model.setting.base.infohintdialog import InfoHintDialog
from common.infohintdialog import InfoHintDialog
from model.setting.getnetinfo import NetCtl
from model.setting.centerapi import CenterApi
from model.cfg.storeinfoparser import StoreInfoParser
# from model.cfg.storeinfoparser import StoreInfoParser
import model.setting.globalfunc
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,350)
        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.setSpacing(20)
        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,2,0)
        miniLayout.addWidget(self.comboNet,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.setLayout(vLayout)
        
        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.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
                print netName,info["netName"]
            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.close()
            InfoHintDialog(u"中心不能为空!").exec_()
            return 

        centerList0 = StoreInfoParser.instance().getCenterList()
        if(centerList0==0 or centerList0==None):
            pass
        else:
            centerList = json.loads(centerList0)
            for i in centerList:
                if (i == name):
                    self.close()
                    InfoHintDialog(u'已经存在该中心名称').exec_()
                    return
            
            for i in centerList:
                if(i==self.centerInfo["netName"]):
                    centerList.pop(i)
                    temp={}
                    temp["centerName"]=str(unicode(name,"utf-8"))
                    temp["centerIp"]=str(ip)
                    temp["networkName"]=str(net)
                    temp["centerPort"]=str("None")
                    centerList[temp["centerName"]]=temp
                    StoreInfoParser.instance().setCenterList(json.dumps(centerList, ensure_ascii=False))
                    break
        self.close()
        InfoHintDialog(u"更新成功!").exec_()
        self.emit(SIGNAL("updateCenter_Date"))
        
    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(",")
                #print list
                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()

