#coding:utf-8
import json
import os
import sys
import time


from base.storeinfoparser import StoreInfoParser
import common
from setting.logrecord import LogRecord
from PyQt4.QtCore import QObject, QFileInfo, QString, QFile, QIODevice,\
    QDateTime, QTime, QDate, QDir


reload(sys)
sys.setdefaultencoding( "utf-8" )

class CenterApi(QObject):
    def __init__(self,parent = None):
        super(CenterApi,self).__init__(parent)

    #显示平台当前设置，保存在一个文件中，并且返回一个列表。
    def getCurSet(self):

        
        ip_port = StoreInfoParser.instance().getCurrenCenter()
        list = ip_port.split(":")
        center = list[0]
        port = list[1]
        if(len(list)>2):
            ssl = list[2]
        else:
            ssl = "false"
        return [center,port,ssl]
    #得到证书
    def getCaFile(self,ip,wget):
        caDir = QFileInfo(common.commondata.CA_NAME)
        if (not caDir.isDir()):
            os.system("mkdir " + common.commondata.CA_NAME)
        
        cmd = wget+ip+"/ca.pem"
        result = os.system(str(cmd))
  
        if (result == 0):
            time.sleep(1)
        else:
            os.system("rm -rf " + common.commondata.CA_NAME + "/ca_temp.pem")
            return False
        
        os.system("mv " + common.commondata.CA_NAME + "/ca_temp.pem " + common.commondata.CA_NAME + "/smep_ca.pem")
        return True
    
    #保存当前设置
    def saveCurSet(self,serverip,serverport,wget,ssl,caName):
        if(not self.getCaFile(serverip+":"+serverport , wget)):
            return -1
        cmd = QString("diff ") + common.commondata.CA_NAME + QString("/smep_ca.pem ") + common.commondata.CA_STORY_DIR + "/" + caName + " > " + common.commondata.CA_COMPARE_RESULT
        ok = os.system(str(cmd))
        if (not QFile.exists(common.commondata.CA_COMPARE_RESULT)):
            return -1
        file_ca = QFile(common.commondata.CA_COMPARE_RESULT)
        
        if(not file_ca.open(QIODevice.ReadOnly)):
            file_ca.close()
            return -1
        #证书内容相同时
        if (file_ca.size() != 0):
            return -3

        s = serverip+ ":" +serverport + ":" + ssl
        StoreInfoParser.instance().setCurrenCenter(s)
        
        return 0
    
    def addNetSwitchItem(self,centerName,centerIp,centerPort,ssl,centerID,networkName,netSwitch):
        #根据时间设置证书的名字
        dt = QDateTime()
        time = QTime()
        date = QDate()
        dt.setTime(time.currentTime())
        dt.setDate(date.currentDate())
        currentDate = dt.toString("yyyy-MM-dd-hh-mm-ss")
        caName = currentDate.split("-").join("") + ".pem"
    
        #把证书移动到相应的目录下
        ca = QDir(common.commondata.CA_STORY_DIR)
        if (not ca.exists()):
            if (not ca.mkdir(common.commondata.CA_STORY_DIR)):
                return -2
        cmd = QString("mv ") + common.commondata.CA_NAME + QString("/smep_ca.pem ") + common.commondata.CA_STORY_DIR + "/" + caName
        print (cmd)
        ok = os.system(str(cmd))
        print ("ok:",ok)
        if (ok != 0):
            return -3
        
        content = unicode(centerName, "utf-8") + ":" + centerIp + ":" + centerPort + ":" + ssl + ":" + caName + ":" + centerID + ":" + networkName + ":" + netSwitch

        s = content
        centerList0 = StoreInfoParser.instance().getNetworkSwitch()

        centerList = []
        if centerList0:
            centerList = json.loads(centerList0)
        
        centerList.append(str(s))
        
        StoreInfoParser.instance().setNetworkSwitch(json.dumps(centerList, ensure_ascii=False))
        return 0
    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 setNetworkSwitch(self,centerName,centerIp,centerPort,ssl,centerID,networkName,netSwitch):#检查重复
        """
        #判断文件networkSwitch.conf是否存在，如果不存在就创建该文件，把输入的有效信息写入该文件
        if (not QFile.exists(commondata.CENTER_SWITCH_NETWORK)):
            result = self.addNetSwitchItem(centerName, centerIp, centerPort, ssl, centerID, networkName)
            return result
        else:
            #如果存在则比较输入的有效信息和文件中的内容是否重复
            file_switch = QFile(commondata.CENTER_SWITCH_NETWORK)
            if(not file_switch.open(QIODevice.ReadOnly)):
                file_switch.close()
                return -1
            s = QTextStream(file_switch);
            contentList = s.readAll().split("\n")
            file_switch.close()
            for i in range(len(contentList)-1):
            #for (int i = 0; i < contentList.size()-1; i++)
                if (contentList[i].isEmpty() or contentList[i].isNull()):
                    continue
                subContent = contentList[i].split(":")
                netName = subContent[0]
                ca_name = subContent[4]
    
                #网络名称相同时
                if (netName == centerName):
                    return -4
                cmd = QString("diff ") + commondata.CA_NAME + QString("/smep_ca.pem ") + commondata.CA_STORY_DIR + "/" + ca_name + " > " + commondata.CA_COMPARE_RESULT;
                ok = os.system(str(cmd))
                if (not QFile.exists(commondata.CA_COMPARE_RESULT)):
                    return -1
                file_ca = QFile(commondata.CA_COMPARE_RESULT)
                if(not file_ca.open(QIODevice.ReadOnly)):
                    file_ca.close()
                    return -1
                #证书内容相同时
                if (file_ca.size() == 0):
                    return -6
            #如果不重复，则将输入的有效信息写入该文件中，
            result = self.addNetSwitchItem(centerName, centerIp, centerPort, ssl, centerID, networkName)
            return result
        """
        
        contentList0 = StoreInfoParser.instance().getNetworkSwitch()

        contentList = []
        if contentList0:
            contentList = json.loads(contentList0)
        
        
        
        for i in range(len(contentList)):
        
            if (contentList[i] == ""):
                continue
            subContent = contentList[i].split(":")
            netName = subContent[0]
            ca_name = subContent[4]
            #网络名称相同时
            if (netName == centerName):
                return -4
            cmd = QString("diff ") + common.commondata.CA_NAME + QString("/smep_ca.pem ") + common.commondata.CA_STORY_DIR + "/" + ca_name + " > " + common.commondata.CA_COMPARE_RESULT;
            ok = os.system(str(cmd))
            if (not QFile.exists(common.commondata.CA_COMPARE_RESULT)):
                return -1
            file_ca = QFile(common.commondata.CA_COMPARE_RESULT)
            if(not file_ca.open(QIODevice.ReadOnly)):
                file_ca.close()
                return -1
            #证书内容相同时
            if (file_ca.size() == 0):
                return -6
        #如果不重复，则将输入的有效信息写入该文件中，
        result = self.addNetSwitchItem(centerName, centerIp, centerPort, ssl, centerID, networkName,netSwitch)
        return result
    
    def getNetSwitchList(self):#获得文件中平台地址的一个列表
        netSwitchList = []
        LogRecord.instance().logger.info(u"进入centerapi的getNetSwitchList函数，获取文件的平台列表")
        contentList0 = StoreInfoParser.instance().getNetworkSwitch()
        LogRecord.instance().logger.info(u"将获取的数据转换为一个真正的列表")
        if not contentList0:
            return netSwitchList
        
        contentList = json.loads(contentList0)
        for i in range(len(contentList)):
            subNetList = {}
            if (contentList[i] == ""):
                pass
            elif type(contentList[i]) == type(subNetList):
                pass
                
            else:
                subList = contentList[i].split(":")
                subNetList["netName"] = subList[0]
                subNetList["netIp"] = subList[1]
                subNetList["netPort"] = subList[2]
                subNetList["netSsl"] = subList[3]
                subNetList["netCaName"] = subList[4]
                subNetList["networkName"] = subList[6]
                subNetList["netSwitch"] = subList[7]
                netSwitchList.append(subNetList)
                
        LogRecord.instance().logger.info(u"退出函数centerapi的getNetSwitchList函数，返回一个字典的列表") 
        return netSwitchList

   
    def getAutoConfNetFlag(self):#自动登录

        value = StoreInfoParser.instance().getAutoConNetwork()
        if (value == "true" or value == "false"):
            return value
        else:
            return ""
        
    def setAutoConfNetFlag(self,flag):#在设置文件中添加true或者false

        if (flag):
            s = "true"
        else:
            s = "false"
            
        StoreInfoParser.instance().setAutoConNetwork(s)

    def delNetWorkSwitchItem(self,caName):#删除平台以及证书
        if (QFile.exists(QString("%1/smep_ca.pem").arg(common.commondata.CA_NAME))):
            #判断当前删除的网络的证书是否与下载证书相同
            diffCmd = "diff " + common.commondata.CA_NAME + "/smep_ca.pem " + common.commondata.CA_STORY_DIR + "/" + caName + " > " + common.commondata.CA_COMPARE_RESULT
            isok = os.system(str(diffCmd))
            
            if (not QFile.exists(common.commondata.CA_COMPARE_RESULT)):
                return -1
            file_ca = QFile(common.commondata.CA_COMPARE_RESULT)
            if(not file_ca.open(QIODevice.ReadOnly)):
                file_ca.close()
                return -2
            #证书内容相同时
            if (file_ca.size() == 0):
                file_ca.close()
                #删除证书
                rmCmd =  QString("rm -rf ") + common.commondata.CA_NAME + QString("/smep_ca.pem")
                ok = os.system(str(rmCmd))
                if (ok != 0):
                    return -3
 
                s = ""
                StoreInfoParser.instance().setCurrenCenter(s)
        sedCmd = QString("rm -rf %3/%4").arg(common.commondata.CA_STORY_DIR).arg(caName)
        ok = os.system(str(sedCmd))
        if (ok != 0):
            return -1
        contentCenterList0 = StoreInfoParser.instance().getNetworkSwitch()
        contentCenterList = json.loads(contentCenterList0)

        text = self.getText(contentCenterList, caName)

        if text == "":
            return "not in"
        contentCenterList.remove(text)

        StoreInfoParser.instance().setNetworkSwitch(json.dumps(contentCenterList, ensure_ascii=False)) 
        return 0
    def getText(self,lst,text):
        for i in range(len(lst)):
            if QString(lst[i]).contains(text):
                return lst[i]
        return ""


    def restartNetwork(self):
    
        cmd = QString("service network restart");
        ok = os.system(str(cmd))
        if (ok != 0):
            return False
        return True
    
