#coding:utf-8

from PyQt4.QtCore import QObject,SIGNAL,QUrl,QString,QByteArray,QTextCodec,QCryptographicHash,QEventLoop,QTimer,QFile,QIODevice,QTextStream,QStringList
#from PyQt4.QtGui import QApplication,QWidget
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest, QSslSocket, QSslConfiguration,QSsl
from PyQt4.QtXml import QDomDocument,QDomNode,QDomNodeList,QDomElement
import os
from dekstop.userapi import UserApi
from common import commondata
from PyQt4.Qt import SLOT


class Hostop(QObject):
    def __init__(self,parent=None):
        super(Hostop,self).__init__(parent)
        
    
    def getHostFile(self):
        if (not QFile.exists(commondata.HOSTS_FILE)):
            return -1
        file_con = QFile(commondata.HOSTS_FILE)
        if(not file_con.open(QIODevice.ReadOnly)):
            file_con.close()
            return -1
        if(file_con.size()==0):
            file_con.close()
            return -2
        fs = QTextStream(file_con)
        hostcon = fs.readAll()
        return hostcon

    def getHostList(self):
        #读取/etc/hosts文件
        res = self.getHostFile()
        if( -1 == res):
            return [] #读ｈｏｓｔ文件失败
        elif(-2 ==res ):
            return [] #ｈｏｓｔ文件为空
        elif(res == ""):
            return []
    
        temp = res.split("\n")
        hostList = []
        for i in range(len(temp)):
            if( temp[i].startsWith("#") ):
                continue
            temp[i]= temp[i].simplified()
            str = temp[i].split(" ")
            num = len(str)
            if( num > 1):
                host = {}
                host["hostip"] = str[0]
                host["hostdes"] = str[1]
                hostList.append(host)
        return hostList

   