#coding:utf-8

from PyQt4.QtGui import QDesktopServices
from PyQt4.QtCore import QObject,QFile,QIODevice,QString,QTextStream

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

    def checkDaomainV(self,name):
        list=self.getHostList(self.readHostFile(self.getHostPath()))
        for i in range(len(list)):
            if(len(list[i])>1):
                if(list[i]["name"]==name):
                    return False
        return True

    def checkDaomainL(self,name):
        list=self.getHostList(self.readHostFile(self.getHostPath()))
        for i in range(len(list)):
            if(len(list[i])>1):
                if(list[i]["name"]==name):
                    return i
        return -1

    def addDomainV(self,ip,name):
        fp = file(self.getHostPath())
        s = fp.read()
        fp.close()
        a = s.split('\n')
        addv=ip+" "+name
        a.insert(0,str(addv))
        s = '\n'.join(a)
        fp = file(self.getHostPath(), 'w')
        fp.write(s)
        fp.close()

    def getHostPath(self):
        fontsLocation  = QDesktopServices.storageLocation(QDesktopServices.FontsLocation)
        pathSystem=""
        if(not fontsLocation.isEmpty() and not fontsLocation.isNull()):
            pathList = fontsLocation.split("\\")
            if(len(pathList)>2):
                pathSystem = str(pathList[0])+str("\\")+str(pathList[1])+str("\\System32\\drivers\\etc\\hosts")
            return pathSystem
        return ""

    def readHostFile(self,center_switch_network1):
        file_switch1=QFile.exists(center_switch_network1)
        if(file_switch1!=0):
            file_switch1=QFile(center_switch_network1)
            if(file_switch1.open(QIODevice.ReadOnly)==0):
                return QString("")#文件没有打开
            s=QTextStream(file_switch1)
            tempList1=s.readAll()
            # print tempList1
            file_switch1.close()
            return tempList1
        else:
            return QString("")#目录没有打开

    def getHostList(self,value):#value是QString类型的变量
        if(value.startsWith("#")):
            return []
        hostList=[]
        tempv=value.split("\n")
        for i in range(len(tempv)):
            if(len(tempv[i])>1):
                tempv2=tempv[i].split(" ")
                if(len(tempv2)>1):
                    tempv3={}
                    tempv3["ip"]=tempv2[0].trimmed()
                    tempv3["name"]=tempv2[1].trimmed()
                    hostList.append(tempv3)

        return hostList




