#coding=utf-8

"""
create for pbc on 2015.08.06 

for restart network ... 
"""

import commands, json, sys, re, os

from PyQt4.Qt import QObject

from base.storeinfoparser import StoreInfoParser
from setting.logrecord import LogRecord


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

class RestartNetwork(QObject):
    def __init__(self,parent=None):
        super(RestartNetwork,self).__init__(parent)
        
    def checkIpConnection(self,ip):
        cmd = "ping %s -c 2" % ip
        get_value = commands.getstatusoutput(cmd)[1]
        ret = str(get_value).find("time=")
        if(ret < 0):
            return False
        else:
            return True  
        
    def checkAutoLogin(self):   
        value_list = StoreInfoParser.instance().getLoginSet()
        if(value_list == ""):
            return False,""
        elif(len(value_list.split(',')) == 4):
            temp_value = value_list.split(',')
            if(len(temp_value) > 3):
                return True,temp_value[3]
            return False,""
        else:
            return False,""
        
    def getloginCenterIp(self,centerName):
        value_list = StoreInfoParser.instance().getNetworkSwitch()
        value = json.loads(value_list)
        for index_value in range(len(value)):
            temp_list1 = value[index_value].split(':')
            if(len(temp_list1) > 2):
                if temp_list1[0] == centerName:
                    pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
                    matchObj = re.match(pattern, unicode(temp_list1[1]))
                    if matchObj:
                        return temp_list1[1]
                    else:
                        return ""
        return ""
    

    def restartNetworkFun(self):
        try:
            temp,value = self.checkAutoLogin()
            ret_ip = self.getloginCenterIp(value)
            if ret_ip != "":
                ret_b = self.checkIpConnection(ret_ip)
                if not ret_b:
                    os.system("service network restart")
                    
        except Exception, e:
            LogRecord.instance().logger.info(str(e.message))
            
            
# _RestartNetwork= RestartNetwork()
# _RestartNetwork.restartNetworkFun()

        
        
        