#coding:utf-8
'''
Created on Sep 4, 2014
@author: root
'''
import commands
import json
import os

from PyQt4.QtCore import QFile, QDateTime, QTime, QDate, QString, QObject

from base.storeinfoparser import StoreInfoParser


class NetCtl(QObject):
    _instance = 0
    def __init__(self,parent=None): 
        super(QObject,self).__init__(parent)      

    #获取网卡
    def getEthList(self):#返回一个网卡列表
        """
        create for pbc 
                获取网卡列表
        """
        netcardList = "".join(commands.getstatusoutput("ls /sys/class/net")[1]).split("\n")
        validNetCardList = [netcard for netcard in netcardList if netcard not in ["br0", "lo", "breth0", "virbr0-nic", "virbr0"]]
        return validNetCardList
    
    def setCurrentNetworkInfo(self,netName,ip,ID): #设置本地当前使用网络

        if (QString(netName).startsWith("dhcp")):
            s = netName + ":" + "dhcp" + ":" + ID
        else:
            s = netName + ":" + ip + ":" + ID
            
        StoreInfoParser.instance().setCurrentLocalNetwork(s)
        
    def getCurrentNetworkInfo(self): #返回本地当前使用网络

        info = StoreInfoParser.instance().getCurrentLocalNetwork()
        return info
    
    def addNetAddressItem(self,netaddress,addressType):#向文件中写入内容
        localNetList0 = StoreInfoParser.instance().getLocalNetworkList()
        localNetList = []
        if localNetList0:
            localNetList = json.loads(localNetList0)
        
        #根据时间设置证书的名字
        dt = QDateTime() 
        time = QTime()
        date = QDate()
        dt.setTime(time.currentTime())
        dt.setDate(date.currentDate())
        currentDate = dt.toString("yyyy-MM-dd-hh-mm-ss")
        
        addressID = currentDate.split("-").join("") + ".id"
    
        #网络地址类型为动态时
        if (addressType == "dhcp"):
            netCardName = netaddress["netCard"]
            content = unicode((QString("dhcp-") + netCardName), "utf-8") + ":" + netCardName + ":" + addressID
            s = content
        else:
            netName = netaddress["netName"]
            netIp = netaddress["netIp"]
            netMast = netaddress["netMast"]
            netGate = netaddress["netGate"]
            netDNS1 = netaddress["netDNS1"]
            netDNS2 = netaddress["netDNS2"]
            netCard = netaddress["netCard"]
    
            if (QString(netName).startsWith("dhcp")):
                errmsg = u"禁用以dhcp为开头的网络名称！"
                return False
            if (netGate == "..." or netGate == ""):
                netGate = "Empty"
            if (netDNS1 == "..." or netDNS1 == ""):
                netDNS1 = "Empty"
            if (netDNS2 == "..." or netDNS2 == ""):
                netDNS2 = "Empty"
            content = unicode(netName, "utf-8") + ":" + netIp + ":" + netMast + ":" + netGate + ":" + netDNS1 + ":" + netDNS2 + ":" + netCard + ":" + addressID
            s = content
            
        localNetList.append(str(s))
        StoreInfoParser.instance().setLocalNetworkList(json.dumps(localNetList, ensure_ascii=False))
        return True
    
    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 addNetAddress(self,netaddress,addressType):#去除文件重复
        #网络地址文件不存在时
        errmsg = ""
       
        contentList0 = StoreInfoParser.instance().getLocalNetworkList()
        contentList = []
        if contentList0:
            contentList = json.loads(contentList0)
        
        addNetName = netaddress["netName"]
            
        if (addressType == "dhcp"):
            card = netaddress["netCard"]
            addNetName += "-" + card
            
            
        for i in range(len(contentList)):
            if (contentList[i] == ""):
                continue
            subContent = contentList[i].split(":")
            netName = subContent[0]
            #网络名称相同时
            if (netName == addNetName):
                if (addressType == "dhcp"):
                    errmsg = "dhcpnettoomany"
                    return False,errmsg
                errmsg = "netnametoomany"
                print (errmsg)
                return False,errmsg
            
        #如果不重复，则将输入的有效信息写入该文件中，
        res = self.addNetAddressItem(netaddress, addressType)
        if (not res):
            return False,errmsg
        return True,errmsg
    def getNetAddressList(self):#得到本地网络列表，元素为字典
        """changed for wmz for change getNetAddressList """
        net_data ="[]"
        if(QFile.exists("/etc/sysconfig/client/net_cfgs")):
            f = open('/etc/sysconfig/client/net_cfgs')
            data = f.read()
            if data:
                net_data = data                     
            f.close()
            
        netAddressList=json.loads(net_data)
        return netAddressList  
          
   
   
        

    

    def delNetAddressItem(self,addressID):#从本地列表中删除一个当地网络
       
            
        contentCenterList0 = StoreInfoParser.instance().getNetworkSwitch()
        contentCenterList = []
        if contentCenterList0:
            contentCenterList = json.loads(contentCenterList0)
        
        
        for i in range(len(contentCenterList)):
            if (contentCenterList[i] == ""):
                continue
            if (QString(contentCenterList[i]).contains(addressID)):
                return -3
            
        contentLocalList0 = StoreInfoParser.instance().getLocalNetworkList()
        contentLocalList = []
        if contentLocalList0:
            contentLocalList = json.loads(contentLocalList0)

        text = self.getText(contentLocalList, addressID)
        netName = text.split(":")[0]
        if text == "":
            return "not in"
        contentLocalList.remove(text)
        StoreInfoParser.instance().setLocalNetworkList(json.dumps(contentLocalList, ensure_ascii=False))  
        
        currentNet = StoreInfoParser.instance().getCurrentLocalNetwork()
        
        if QString(currentNet).contains(addressID) or QString(currentNet).contains(netName):
            StoreInfoParser.instance().setCurrentLocalNetwork("")
        
    def getText(self,lst,text):
        for i in range(len(lst)):
            if QString(lst[i]).contains(text):
                return lst[i]
        return ""
    
    def getNetConf(self,command):
        fp = os.popen(command).read()
        result = fp.split("\n")[0]
        return result
    
    
    def removeOldCfg(self,eth): #删除eth0的内容
        filePath = "/etc/sysconfig/network-scripts/ifcfg-" + eth
        if (not QFile.exists(filePath)):
            return False
        else:
            cmd0 = "sed -i '/BOOTPROTO/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd1 = "sed -i '/IPADDR/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd2 = "sed -i '/PREFIX/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd3 = "sed -i '/GATEWAY/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd4 = "sed -i '/NETMASK/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd5 = "sed -i '/DNS1/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd6 = "sed -i '/LAST_CONNECT/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd7 = "sed -i '/PEER/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd8 = "sed -i '/UUID/d' /etc/sysconfig/network-scripts/ifcfg-" + eth

            cmd10 = "sed -i '/DNS2/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd11 = "sed -i '/ONBOOT/d' /etc/sysconfig/network-scripts/ifcfg-" + eth
            cmd12 = "sed -i '/DEVICE/d' /etc/sysconfig/network-scripts/ifcfg-" + eth

            
            
            
            os.system(str(cmd0))  # 执行成功则返回0，否则1
            os.system(str(cmd1))
            os.system(str(cmd2))
            os.system(str(cmd3))
            os.system(str(cmd4))
            os.system(str(cmd5))
            os.system(str(cmd6))
            os.system(str(cmd7))
            os.system(str(cmd8))

            os.system(str(cmd10))
            os.system(str(cmd11))
            os.system(str(cmd12))

            
            
            return True
        
        

        
    def setAuto(self,eth):#设置动态网路
        netcardList = "".join(commands.getstatusoutput("ls /etc/sysconfig/network-scripts/ifcfg-*")[1]).split("\n")
        print (eth)
        for i in netcardList:
            temp = "/etc/sysconfig/network-scripts/ifcfg-" + eth
            temp2 = "/etc/sysconfig/network-scripts/ifcfg-breth0"
            if(i != temp and i != temp2):
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=no' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
            else:
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=yes' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
        
        if eth != "breth0":
            result = self.removeOldCfg("breth0")
            if (result == False):
                return False
            cmd = "echo 'BOOTPROTO=dhcp' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            cmd2 = "echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"

            cmd5 = "echo 'DEVICE=breth0' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
            

            os.system(str(cmd2))
            os.system(str(cmd))
            os.system(str(cmd5))
        else:
            cmd = "sed -i '/ONBOOT/d' " + i
            cmd2 = "echo 'ONBOOT=yes' >> " + i
            os.system(str(cmd))
            os.system(str(cmd2))

        c = os.system("service network restart")
        if c == 0:
            return True
        else:
            return False
        
        


    def setStatic(self,eth,ip,mask,gateway,dns1,dns2):#设置静态网络
        netcardList = "".join(commands.getstatusoutput("ls /etc/sysconfig/network-scripts/ifcfg-*")[1]).split("\n")
        print ("start ,,", netcardList)
        for i in netcardList:
            temp = "/etc/sysconfig/network-scripts/ifcfg-" + eth
            temp2 = "/etc/sysconfig/network-scripts/ifcfg-breth0"
            temp3 = "/etc/sysconfig/network-scripts/ifcfg-lo"
            if(i != temp and i != temp2 and i != temp3):
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=no' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
            else:
                cmd = "sed -i '/ONBOOT/d' " + i
                cmd2 = "echo 'ONBOOT=yes' >> " + i
                os.system(str(cmd))
                os.system(str(cmd2))
        
        if eth != "breth0":
            result = self.removeOldCfg("breth0")
            if(result):
                endeth = "breth0"
                settings7 = "echo " + "'" + "DEVICE=" + endeth + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                os.system(settings7)
                settings0 = "echo " + "'" + "BOOTPROTO=static" + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings1 = "echo " + "'" + "IPADDR=" + str(ip) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings2 = "echo " + "'" + "NETMASK=" + str(mask) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings3 = "echo " + "'" + "GATEWAY=" + str(gateway) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings4 = "echo " + "'" + "DNS1=" + str(dns1) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings5 = "echo " + "'" + "DNS2=" + str(dns2) + "'" + ">> /etc/sysconfig/network-scripts/ifcfg-" + endeth
                settings6 = "echo 'ONBOOT=yes' >> /etc/sysconfig/network-scripts/ifcfg-breth0"
                cmd_ifup = "ifup " + endeth


                a = os.system(str(settings0))
                b = os.system(str(settings1))
                c = os.system(str(settings2))
                d = os.system(str(settings3))
                e = os.system(str(settings4))
                f = os.system(str(settings5))
                g = os.system(str(settings6))
                h = os.system(str(cmd_ifup))
            else:
                return False

            k = os.system("service network restart")
            if a == 0 and b == 0 and c == 0 and d == 0 and e == 0 and f == 0 and g == 0 and k == 0:
                return True
            else:
                return False
        
        
      
    def getCmdLine(self,command):
    
        fp = os.popen(command).read()

        result = fp.split("\n")
        return result
    def getWirelessList(self):
        cmd = "iwconfig"
        output = ""
        status = []
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        else:
            output = ""
        outputList = output.split("\n")
        for i in range(len(outputList)):
            pass
        
    def isNetUsb(self):
        os.system("mv /etc/sysconfig/network-scripts/wlan0 /etc/sysconfig/network-scripts/ifcfg-wlan0")
        ok = os.system("service network restart")
        if ok == 0:
    
            return True
        else:
            os.system("mv /etc/sysconfig/network-scripts/ifcfg-wlan0 /etc/sysconfig/network-scripts/wlan0")
            return False
    