#/usr/bin/python
#coding=utf-8

import  os,sys
if os.name == 'posix' and sys.version_info[0] < 3:
    import subprocess32 as subprocess
else:
    import subprocess

from threading import Thread ,_sleep
import time
from uiWindow.sendCmd.validate.syncCenterClock import SyncCenterClock
from logger.logrecord import LogRecord


class SyncClockThread(Thread):
    def __init__(self,ip_port):
        super(SyncClockThread, self).__init__(None)
        self.__centerTime = SyncCenterClock(ip_port)
        self.setDaemon(True)

    def run(self):
        try:
            LogRecord.instance().logger.info("Sync Center Clock")
            __time = 0
            res = self.__centerTime.checkCenterTime()
            if res[0] == False:
                __err_info = res[1].decode("utf-8")
                LogRecord.instance().logger.error("SyncClockThread:" + str(__err_info))
                return None
            else:
                __time = res[1]
                # print __time/1000.0
                time_struct = time.gmtime(__time/1000.0 + 8 * 60 * 60)   # 北京时间  + 8小时
                __date = "%s-%s-%s %s:%s:%s" % (time_struct.tm_year,time_struct.tm_mon,time_struct.tm_mday,\
                                                time_struct.tm_hour,time_struct.tm_min,time_struct.tm_sec)
                clock_info = "Center Clock time : GTM8  %s (%s) " % (__date,__time)
                LogRecord.instance().logger.info(clock_info)
                # print __date
                args = ["date","-s",__date]
                subprocess.call(args)   # 设置系统时间

                args = ["hwclock","-w"]
                subprocess.call(args)   # 同步系统时钟到硬件时钟

        except Exception:
            LogRecord.instance().logger.exception("SyncClockThread")
    # 停止
    def stop(self):
        if self.isAlive():
            self.join(4)


##############################
# 单 元 测 试
##############################
if __name__ == "__main__":
    pass
    from os import getenv,environ
    if getenv('LOG_STDOUT') == None:
        environ["LOG_STDOUT"] = "stdout"  #
    syncThread = SyncClockThread("192.168.102.33:8080")
    syncThread.run()
    # syncThread.join(10)
