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

from PyQt4.QtCore import QObject, SIGNAL
from PyQt4.QtNetwork import QTcpServer, QHostAddress
import common
from configFileParser import ConfigFileParser
from storeinfoparser import StoreInfoParser
from logrecord import LogRecord
import common 
import globalfunc
import globalvariable

class CloudsTcpServer(QObject):
    _instance = 0 
    def __init__(self):
        super(CloudsTcpServer,self).__init__()
        
        self.myTcpServer = QTcpServer()
        
        ok = self.myTcpServer.listen(QHostAddress.Any, common.SOCKET_PROT)
        if not ok:
            LogRecord.instance().logger.info(u"初始化监听端口%s失败" % common.SOCKET_PROT)
            
        LogRecord.instance().logger.info(u"开启监听云主机成功")
        self.connect(self.myTcpServer,SIGNAL("newConnection()"),self.slotNewConnection);

    def slotNewConnection(self):
        #获取已经建立的连接的子套接字
        LogRecord.instance().logger.info(u"监测到有新的tcp连接")
        self.m_pTcpSocket = self.myTcpServer.nextPendingConnection()
        if self.m_pTcpSocket == None:
            LogRecord.instance().logger.info(u"新的tcp连接错误")
            return
        
        #关联接受客户端发来数据的槽
        self.connect(self.m_pTcpSocket, SIGNAL("readyRead()"), self.dataReceived);
        self.connect(self.m_pTcpSocket, SIGNAL("disconnected()"), self.deleteLaters)
            
    def deleteLaters(self):
        self.m_pTcpSocket.deleteLater()
        
        
    def dataReceived(self):
        #return
        try:
            data = str(self.m_pTcpSocket.readAll())
            self.m_pTcpSocket.close()
            LogRecord.instance().logger.info(u"监测到云主机发来的信息：%s" % data)
            if data:
                contentList = data.split(":")
                if len(contentList) >= 2:
                    if contentList[0] == "TERMINAL_NETWORK_CONFIG":
                        if len(contentList) >= 3:
                            terminalName = contentList[1]
                            valueList = contentList[2:]
                            LogRecord.instance().logger.info(u"记录分配给终端的名称：%s" % terminalName)
                            StoreInfoParser.instance().setTerminalName(terminalName)
                            globalvariable.TERMINAL_NAME = terminalName
                            # globalfunc.changePCMName(terminalName)
                            self.emit(SIGNAL("tcpsocketSignal"), "TERMINAL_NETWORK_CONFIG", valueList)
                        else:
                            LogRecord.instance().logger.info(u"监测到云主机发来的网络配置信息格式有误")
                    elif contentList[0] == "TICHU":
                        value = contentList[1]
                        LogRecord.instance().logger.info(u"从云主机获得提出该学生端命令")
                        self.emit(SIGNAL("tcpsocketSignal"), "TICHU", value)
                    elif contentList[0] == "shutdown":
                        value = contentList[1]
                        LogRecord.instance().logger.info(u"从云主机获得提出该学生端命令")
                        self.emit(SIGNAL("tcpsocketSignal"), "shutdown", value)
                    elif contentList[0] == "poweroff":
                        value = contentList[1]
                        LogRecord.instance().logger.info(u"从云主机获得提出该学生端命令")
                        self.emit(SIGNAL("tcpsocketSignal"), "poweroff", value)
                    elif contentList[0] == "reset":
                        value = contentList[1]
                        LogRecord.instance().logger.info(u"从云主机获得提出该学生端命令")
                        self.emit(SIGNAL("tcpsocketSignal"), "reset", value)
                    
                    elif contentList[0] == "TERMINAL_NAME":
                        terminalName = contentList[1]
                        LogRecord.instance().logger.info(u"从云主机获得学生机的名称")
                        self.emit(SIGNAL("tcpsocketSignal"), "TERMINAL_NAME", terminalName)
                        
                else:
                    LogRecord.instance().logger.info(u"监测到云主机发来的信息格式有误")
            else:
                LogRecord.instance().logger.info(u"监测到云主机发来的信息内容为空")
        except:
            LogRecord.instance().logger.info(u"接收云主机发来的信息失败msgecept")
                
        
        
# from PyQt4.QtGui import QApplication
# import sys
# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = CloudsTcpServer()
#     
#     app.exec_()
    
    
    
        