#coding:utf-8
'''
Created on Feb 3, 2015

@author: root
'''

from PyQt4.QtCore import QThread

from networkmanager import NetworkManager
from vminfomanager import VMInfoManager
from storeinfoparser import StoreInfoParser
import time
import json
import globalvariable
import globalfunc
import threading
from logrecord import LogRecord
import commands
import os 

class UpdateThread(QThread):
    def __init__(self,parent=None):
        super(UpdateThread,self).__init__(parent=None)
        self.vmtype = StoreInfoParser.instance().getVmType()
        self.license = "True"
        self.lessonlist = []
        self.offlessonlist = []
        self.vminfo = []
        self.auto = True
        self.coursename = ""
        self.postVmInfo = {}
        self.checkFlag = True
        self.pCheckNet = threading.Thread(target=self.checkNetState)
        self.pCheckNet.start()
    
    
    def stopUpdateThread(self):
        self.auto = False
        
    def getThreadStatus(self):
        return self.auto
        
    def restartNet(self):
        ok = -1
        sysType = globalfunc.getLinuxOperationSystemType()

        if sysType and sysType == "Ubuntu 12.04":
            ok = os.system("/etc/init.d/networking restart")
        elif sysType and sysType == "Ubuntu 13.04":
            ok = os.system("/etc/init.d/networking restart")
        elif sysType and sysType == "Ubuntu 14.04":
            ok = os.system("ifdown eth0 && ifup eth0")
        elif sysType and sysType == "CentOS 6.5":
            ok = os.system("service network restart")
        elif sysType and sysType == "CentOS 7.0":
            ok = os.system("systemctl restart network.service")
            time.sleep(10)
        else:
            ok = os.system("service network restart")

    def checkNetState(self):        
        while self.checkFlag:
            try:
                if globalfunc.get_network_type() == "dhcp":
                    if globalfunc.get_ip_address() == "0.0.0.0":
                        statusOutput = commands.getstatusoutput("cat /sys/class/net/br0/operstate")
                        if statusOutput[0] == 0:
                            output = statusOutput[1]
                            LogRecord.instance().logger.info("output:%s" % output)					
                            if output == "up":
                                self.restartNet()
                            time.sleep(10)					  
                    else:
                        self.checkFlag = False
            except Exception as e:
                time.sleep(10)

    def run(self):
        self.auto = True
        while self.auto:
            try:
                #注册学生机信息
                NetworkManager.instance().postTerminalInfo() 
                #获取云教室类型
                vmtype = NetworkManager.instance().getVMType()
                self.setVmType(vmtype)
                #获取云主机的运行状态可用或者不可用
                serverState = VMInfoManager.instance().getCurCloudServerState()
                if serverState != "enable":
                    time.sleep(5)
                    continue
                #获取当前是否正在上课
                NetworkManager.instance().setClassState()
                #获取正在上课状态下的虚拟机名称，并设置到本地的globalvariable.CLASS_STATUS_VM_NAME
                NetworkManager.instance().setClassVMName()
                #获取正在上课时的课程名称
                coursename = NetworkManager.instance().getRunningCourseName()
                self.setCourseName(coursename)
                
                if coursename != "" and coursename != None:
                    #获取正在上课时云桌面的信息
                    vmName = globalvariable.CLASS_STATUS_VM_NAME
                    vmInfo = NetworkManager.instance().getVMInfo(vmName)
                    self.setVmInfo(vmInfo)
                
                #获取课程列表信息并保存
                NetworkManager.instance().refreshLessonInfo()
                lessonlist = VMInfoManager.instance().getLessonListInfo()
                self.setVmLessonList(lessonlist)
                #获取课程列表信息并保存，离线列表可以判断是否分配到虚拟机
                NetworkManager.instance().refreshOnlineLessonInfo()
                offLessonList = VMInfoManager.instance().getOnlineLessonListInfo()
                self.setOffvmLessonList(offLessonList)
                
                #更新授权类型 
                lisencedate = NetworkManager.instance().getLicenseDate()
                self.setLisence(lisencedate)
                
                #更新USB透传的状态值并保存到本地
                usbValue = NetworkManager.instance().getUSBState()
                if usbValue is not None:
                    StoreInfoParser.instance().setUsbState(usbValue)
                else:
                    StoreInfoParser.instance().setUsbState("False")
                    
                #更新NET的状态值并保存到本地
                netValue = NetworkManager.instance().getNetState()
                if netValue is not None:
                    StoreInfoParser.instance().setNetState(netValue)
                else:
                    StoreInfoParser.instance().setNetState("False")
                    
                if vmtype == "online":
                    time.sleep(5)
                elif vmtype == "offline":
                    #发送离线状态下的虚拟机运行状态信息
                    NetworkManager.instance().postVmStateInfo(self.postVmInfo)
                    time.sleep(2)
                else:
                    time.sleep(5)
            except Exception as e:
                time.sleep(5)
    def setVmInfoState(self,stateInfo):
        self.postVmInfo = stateInfo
    def getVmInfoState(self):
        return self.postVmInfo
    
    def setVmType(self,vmtype):
        if vmtype == "" or vmtype == None:
            vmtype = StoreInfoParser.instance().getVmType()
        self.vmtype = vmtype
        StoreInfoParser.instance().setVmType(vmtype)
        
    def getVmType(self):
        return self.vmtype
    def setCourseName(self,coursename):
        self.coursename = coursename
        globalvariable.RUNNING_COURSE = coursename
    def getCourseName(self):
        return globalvariable.RUNNING_COURSE
    
    def setLisence(self,lisence):
        if lisence == "" or lisence == None:
            lisence = StoreInfoParser.instance().getVmType()
        self.license = lisence
        StoreInfoParser.instance().setLicense(lisence)
        
    def getLisence(self):
        return self.license
    
    def setVmLessonList(self,vmlessonlist):
        self.lessonlist = vmlessonlist
        if vmlessonlist == False:
            return
            #StoreInfoParser.instance().setLessonList(json.dumps({}),ensure_ascii=False)
        StoreInfoParser.instance().setLessonList(json.dumps(vmlessonlist))
        
    def getVmLessonList(self):
        return self.lessonlist
    
    def setOffvmLessonList(self,vmofflessonlist):
        self.offlessonlist = vmofflessonlist
        StoreInfoParser.instance().setOffLessonList(json.dumps(vmofflessonlist))
    def getOffvmLessonList(self):
        return self.offlessonlist
    
    def getVmInfo(self):
        
        return globalvariable.VM_INFO
    
    def setVmInfo(self,vminfo):
        self.vminfo = vminfo
        globalvariable.VM_INFO = vminfo
        
