# -*- coding: utf-8 -*-  

from PyQt4.QtCore import QObject, QEventLoop, QString, QTimer, SIGNAL, QUrl, QByteArray, QTextCodec, SLOT
# from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest, QSslConfiguration, QSslSocket, QSsl,\
#                             QNetworkReply
import time
import requests
import common
import json
import os
#import ethtool
from vminfomanager import VMInfoManager
from configFileParser import ConfigFileParser
from storeinfoparser import StoreInfoParser
import globalfunc
import globalvariable
import requestinfo
from logrecord import LogRecord

class NetworkManager(QObject):
    _instance = 0 
    def __init__(self):
        super(NetworkManager,self).__init__()
        
    def connectServer(self):
        #连接服务器
        jsonInfo = self.getCloudsServerState()
        state = False
        if jsonInfo is not None:
            state = False
            if jsonInfo:
                if jsonInfo.has_key('state'):
                    state = jsonInfo["state"]
            VMInfoManager.instance().setCurCloudServerState(state)
            time.sleep(1)
            return True
        VMInfoManager.instance().setCurCloudServerState(state)
        time.sleep(2)
        return False

    def getVMInfo(self, vmname):
        """根据虚拟机的名称得到虚拟机的信息"""
        vmList = []
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return []

        url = "https://%s:8001/vms/%s" % (serverIp, vmname)

        infoValue = requestinfo.Requests.instance().getRequestInfo(url)
        if infoValue is not None:
            vmList.append(infoValue)
        return vmList
        
    def getVMPort(self,vmname):
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        url = "https://%s:8001/vms/getGraphicsPort" % serverIp
        payload = {"vmname":vmname}
        infoValue = requestinfo.Requests.instance().postRequestInfo(url, payload, True)
        #print infoValue
        if infoValue == False:
            return False
        else:
            if infoValue.has_key("port"):
                return infoValue["port"]
            else:
                return False
    
    def getVMType(self):
        """根据虚拟机的名称得到虚拟机的信息"""
        #return "online"
        vmtype = ""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None

        url = "https://%s:8001/infoconfigstates/getAuthType" % (serverIp)

        infoValue = requestinfo.Requests.instance().getRequestInfo(url)
        if infoValue is not None:
            vmtype = infoValue

        return vmtype
    def getRunningCourseName(self):
        
        coursename = ""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None

        url = "https://%s:8001/infoconfigstates/getLessonName" % (serverIp)

        infoValue = requestinfo.Requests.instance().getLicenseRequestInfo(url)
        if infoValue is not None:
            coursename = infoValue
        #globalvariable.CLASS_STATUS_VM_NAME = coursename
        return coursename
    
    def getLicenseDate(self):
        licenses = ""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None
        url = "https://%s:8001/licences/checkLicenseDate" % (serverIp)
        infoValue = requestinfo.Requests.instance().getLicenseRequestInfo(url)
        if infoValue is not None:
            licenses = infoValue

        return licenses
    
    def getUsbState__(self):
        state = ""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None
        url = "https://%s:8001/infoconfigstates/getUsbState" % (serverIp)
        infoValue = requestinfo.Requests.instance().getUsbStateRequestInfo(url)
        if infoValue is not None:
            state = infoValue
        return state
    
    def refreshVMInfo(self):
        """刷新所有虚拟机列表信息,not use"""
        jsonInfo = self.getVMListInfo()
        if jsonInfo is not None:
            VMInfoManager.instance().setVMSInfo(jsonInfo)
            return True
        else:
            #VMInfoManager.instance().setVMSInfo([])
            return False
    
    def refreshLessonInfo(self):
        """刷新课程列表信息"""
        jsonInfo = self.getLessonListInfo()
        if jsonInfo is not None:
            VMInfoManager.instance().setLessonListInfo(jsonInfo)
            return True
        else:
            #VMInfoManager.instance().setLessonListInfo([])
            return False
    def refreshOnlineLessonInfo(self):
        """刷新shangxian课程列表信息"""
        jsonInfo = self.getOnlineLessonListInfo()
        if jsonInfo != False:
            VMInfoManager.instance().setOnlineLessonListInfo(jsonInfo)
            return True
        else:
            #VMInfoManager.instance().setOnlineLessonListInfo([])
            return False

    def getRequestInfo(self, url):
        """得到请求的信息"""
        infoValue = requestinfo.Requests.instance().getRequestInfo(url)
        return infoValue
    def getPostRequestInfo(self, url):
        """得到请求的信息"""

        mac = globalfunc.get_mac_address()
        payload = {"mac":mac}
        infoValue = requestinfo.Requests.instance().postRequestInfo(url, payload, True)
        if infoValue == False:
            return False
        
        return infoValue

    def getLessonListInfo(self):
        """得到课程列表信息"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None
 
        url = "https://%s:8001/courselibs/showCourseLibs" % serverIp
        return self.getRequestInfo(url)
    def getOnlineLessonListInfo(self):
        """得到上线课程列表信息"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return False

        url = "https://%s:8001/courselibs/OnlineCourseLibs" % serverIp
        return self.getPostRequestInfo(url)
    
    def postVmStateInfo(self,payload):
        #return
        """vm status"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return
        url = "https://%s:8001/clouddesktops/saveOfflineVmStat" % serverIp
        requestinfo.Requests.instance().postRequestInfo(url, payload)
        LogRecord.instance().logger.info(u"发送VM信息结束")
            
    def postTerminalInfo(self):
        """注册终端信息"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return

        terminalName = StoreInfoParser.instance().getTerminalName()
        ip = globalfunc.get_ip_address()
        mac = globalfunc.get_mac_address()
        networkType = globalfunc.get_network_type()
        #networkType = "dhcp"
        if networkType is None:
            LogRecord.instance().logger.info(u"未获取有效的网络类型")
            networkType = "dhcp"

        bootproto = None
        netmask = ""
        gateway = ""
        dns = ""
        if networkType == "static":
            bootproto = "static"
            netmask, gateway, dns = globalfunc.get_netmask_gateway_dns()
        else:
            bootproto = "dhcp"
        
        payload = {'name':terminalName, "ip":ip, "mac":mac, \
                   "bootproto":bootproto, "netmask":netmask, "gateway":gateway, "dns":dns}
        url = "https://%s:8001/terminals/sign" % serverIp
        terminalName = requestinfo.Requests.instance().getTerminalRequestInfo(url, payload)
        if terminalName == None:
            terminalName = StoreInfoParser.instance().getTerminalName()
            if terminalName == "" or terminalName == None:
                terminalName = ""
        StoreInfoParser.instance().setTerminalName(terminalName)
        globalvariable.TERMINAL_NAME = terminalName
        LogRecord.instance().logger.info(u"注册终端信息")
    def getVMListInfo(self):
        """获取所有虚拟机的列表信息"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None

        url = "https://%s:8001/vms" % serverIp

        return self.getRequestInfo(url)

    
    @classmethod 
    def instance(cls):
        if (cls._instance == 0):
            cls._instance = NetworkManager()
            
        return cls._instance
    
    def settingNetBridge(self, state):
        if state == 'True':
            os.system('iptables -F FORWARD')
            os.system('iptables -P FORWARD ACCEPT')
        else:
            os.system('iptables -F FORWARD')
            str = 'iptables -t filter -A FORWARD -s %s/24 -i br0 -d %s/24 -o br0 -j ACCEPT'
            #ip = ethtool.get_ipaddr('br0').split('.')#get ip of br0 and store as a list["192","168","5","111"]
            ip = globalfunc.get_ip_address().split('.')
            ip[3] = '0'  #list become ["192","168","5","0"]
            ipaddr = '.'.join(ip) #list become a str of "192.168.5.0"
            command = str % (ipaddr, ipaddr)
            os.system('iptables -P FORWARD DROP')
            os.system(command)
        
    def setClassState(self):
        dataList = self.getInfoDataValue()
        if dataList is not None:
            self.parserClassState(dataList)
    
    def getUSBState(self):
        state = None
        dataList = self.getInfoDataValue()
        if dataList is not None:
            state = self.parserUsbState(dataList)
        
        if state is None:
            state = StoreInfoParser.instance().getUsbState()
            if state == "" or state == None:
                state = "True"
              
        return state
    def getNetState(self):
        state = None
        dataList = self.getInfoDataValue()
        if dataList is not None:
            state = self.parserNetState(dataList)
        
        if state is None:
            state = StoreInfoParser.instance().getNetState()
            if state == "" or state == None:
                state = "True"
            
        return state

    def getInfoDataValue(self):
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None

        url = "https://%s:8001/infoconfigstates" % serverIp

        return self.getRequestInfo(url)

    
    def parserUsbState(self, dataList):
        """解析USB的使用状态"""
        usbState = None
        if dataList:
            if dataList[0]:
                for subData in dataList[0]:
                    if subData[2] == 'usbstate':
                        usbState = subData[1]
                        break
        return usbState
    
    def parserNetState(self, dataList):
        """解析Net的使用状态"""
        netState = None
        if dataList:
            if dataList[0]:
                for subData in dataList[0]:
                    if subData[2] == 'networkstate':
                        netState = subData[1]
                        break
        return netState
    
    def parserClassState(self, dataList):
        """解析上课的状态"""
        classState = None
        if dataList:
            if dataList[0]:
                for subData in dataList[0]:
                    if subData[2] == 'classstate':
                        classState = subData[1]
                        break
                if classState:
                    if classState == "True":
                        globalvariable.CLASS_STATUS = True
                    else:
                        globalvariable.CLASS_STATUS = False

    def getTerminalVMsValue(self):
        """得到分配给当前学生机的虚拟机信息"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None

        mac = globalfunc.get_mac_address()
        url = "https://%s:8001/terminalvms/%s" % (serverIp, mac)

        return self.getRequestInfo(url)

            
    def setClassVMName(self):
        """记录上课状态时分配给学生机的虚拟机名称"""
        jsonDir = self.getTerminalVMsValue()
        if jsonDir and jsonDir.has_key("name"):
            globalvariable.CLASS_STATUS_VM_NAME = jsonDir["name"]
        else:
            globalvariable.CLASS_STATUS_VM_NAME = None

    def getCloudsServerState(self):
        """获取云主机的状态"""
        serverIp = StoreInfoParser.instance().getCloudsServerIP()
        if serverIp == None:
            LogRecord.instance().logger.info(u"没有设置云中心IP地址，无法连接云主机")
            return None

        url = "https://%s:8001/cloudhostings/getlocal" % serverIp

        #return self.getRequestInfo(url)
        return requestinfo.Requests.instance().getHostRequestInfo(url)    
    
    
    
    
