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

from PyQt4.QtCore import SIGNAL, QThread
import time
from networkmanager import NetworkManager      
from logrecord import LogRecord  

class LinkServerThread(QThread):
    def __init__(self, parent=None):
        super(LinkServerThread,self).__init__(parent)
        self.isLinkSuccess = False
        self.isStartLink = True
        self.failNum = 0
        
    def run_(self):
        for i in range(1):
            time.sleep(1)
        self.emit(SIGNAL("ConnectSuccess"))
        
    def run(self):
        while self.isStartLink:
            if not NetworkManager.instance().connectServer():
                self.isLinkSuccess = False
                self.emit(SIGNAL("ConnectFailed"), self.failNum)
                LogRecord.instance().logger.info(u"连接云终端失败")

                while not self.isLinkSuccess and self.isStartLink:
                    self.emit(SIGNAL("Connecting"), self.failNum)
                    if NetworkManager.instance().connectServer():
                        self.isLinkSuccess = True
                        time.sleep(7)
                        self.emit(SIGNAL("ConnectSuccess"))
                        self.failNum = 0
                    else:
                        self.failNum += 1
                        self.emit(SIGNAL("ConnectFailed"), self.failNum)
                        LogRecord.instance().logger.info(u"连接云终端失败")
                        if self.isStartLink:
                            time.sleep(5)
            else:
                self.failNum = 0
                time.sleep(7)
                self.emit(SIGNAL("ConnectSuccess"))
                time.sleep(6)
                
    def changeLinkStatus(self, status):
        self.isStartLink = status
        if status:
            self.start()
        else:
            self.failNum = 0
            
            
        