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

import requests
from logger.logrecord import LogRecord

class CheckUpgrade(object):
    "CheckUpgrade"
    omitVersion = ""
    centerVersion = ""
    def __init__(self, url, curVersion):
        pass
        self.__url = url
        self.__curVersion = curVersion

    def requestVersion(self):
        '''
            返回（status，upgradeInfo）
        '''
        url = "http://%s/api/terminals/clientVersion/ubuntu" % self.__url
        LogRecord.instance().logger.info(str(url))
        try:
            recv = requests.get(url, timeout=2)
            recv.raise_for_status()  # 如果响应状态码不是 200，就主动抛出异常
            # print recv.text
            # 判断 是否是 json类型
            if recv.headers['content-type'] != "application/json;charset=UTF-8":
                print recv.headers['content-type']
                raise Exception(" content-type err %s ;not is  application/json" % recv.headers['content-type'])

            # print "-------aaa------"
            # print recv.text
            # print "-----bbb----"

            recvInfo = recv.json()
            if recvInfo == None:
                return False, "checkUpgrade recv.json :  None"

            dict_tmp = recvInfo["result"]
            if dict_tmp == None:
                return False, "checkUpgrade : result == None"

            status = dict_tmp["status"]  # 状态
            # info    = dict_tmp["info"]
            info    = str(dict_tmp["info"].encode('utf-8'))
            # print type(status)
            # print type(info)

            if status != "y":
                return False, "checkUpgrade warning: %s" % info

            if dict_tmp["result"] == None:
                return False, "checkUpgrade error: result_result == None"

            updateInfo_tmp = dict_tmp["result"]


            if updateInfo_tmp["clientType"] != "ubuntu":
                return False, "clientType != ubuntu"

            LogRecord.instance().logger.info(str(updateInfo_tmp))
            #
            upgradeInfo = {
                "update": False,
                "isForced": False,
                "version": None,
                "upgrade_url": None
            }
            upgradeInfo["upgrade_url"] = updateInfo_tmp["upgrade_url"]
            upgradeInfo["version"] = updateInfo_tmp["version"]  # 最新 版本号
            upgradeInfo["isForced"] = updateInfo_tmp["isForced"]
            CheckUpgrade.centerVersion = upgradeInfo["version"]
            # 转换,  ['4','5','0','20160603'] => [4,5,0,20160603]
            def versionsToNums(versions):
                nums = []
                for i in range(len(versions)):
                    num = int(versions[i])
                    nums.append(num)
                # print "转换后",nums
                return nums

            curVersions = self.__curVersion.split(".") # 将 "4, 5, 0, 20160603" =>
                                                       #    ['4','5','0','20160603']
            minVersions = updateInfo_tmp["minVersion"].strip().split(".")

            versions = updateInfo_tmp["version"].strip().split(".")

            curVersionNums = versionsToNums(curVersions)
            minVersionNums = versionsToNums(minVersions)
            versionNums = versionsToNums(versions)
            # print self.__curVersion,upgradeInfo["version"],CheckUpgrade.omitVersion
            # 判断 版本号  与 最新 版本号 相等 取消 版本升级
            if str(self.__curVersion) == str(upgradeInfo["version"]):
                info = "check upgrade curVersion: [%s] == new version:[%s]"%\
                       (str(self.__curVersion),str(upgradeInfo["version"]))

                LogRecord.instance().logger.info(info)
                upgradeInfo["update"] = False
                upgradeInfo["isForced"] = "0"
                return True,upgradeInfo

            if upgradeInfo["isForced"] == "1":
                upgradeInfo["update"] = True
                return True, upgradeInfo

            if self.compareLessVesion(curVersionNums,minVersionNums):
                ''' 当前版本 < 最小版本  '''
                info =  str(curVersionNums) + "<" + str(minVersionNums)
                LogRecord.instance().logger.info(info)

                upgradeInfo["update"] = True
                upgradeInfo["isForced"] = "1"
                return True, upgradeInfo  # 当前版本 小于 最小版本时

            if (self.compareLessVesion(curVersionNums,versionNums)
                and CheckUpgrade.omitVersion != upgradeInfo["version"]):
                ''' 当前版本 < 最新版本号  '''

                info =  str(curVersionNums) + "<" + str(versionNums)
                LogRecord.instance().logger.info(info)

                upgradeInfo["update"] = True
                # upgradeInfo["update"] = True
                return True, upgradeInfo  # 当前版本 小于 最新版本版本时

            upgradeInfo["update"] = False
            upgradeInfo["isForced"] = "0"
            return True, upgradeInfo

        except requests.exceptions.ConnectionError as e:
            info =  self.__doc__ + str(e.message)
            LogRecord.instance().logger.error(info)
            return False, "检查升级,网络连接异常"

        except requests.exceptions.Timeout as e:
            info =  self.__doc__ + str(e.message)
            LogRecord.instance().logger.error(info)
            return False, "检查升级超时异常"

        except Exception as e:
            info =  self.__doc__ + str(e.message)
            LogRecord.instance().logger.error(info)
            return False, "upgread err" + str(e.message)


    ## ============== 比较 verMin < verMax ===============
    #  [4, 4, 0, 20160510] < [4, 5, 0, 20160603] 返回 true
    #  [4, 6, 2, 20160654] < [4, 5, 0, 20160603] 返回 False
    #  [4, 5, 0, 20160603] < [4, 5, 0, 20160603] 返回 False
    #------------------------------------------------------
    def compareLessVesion(self,verMin, verMax):
        "ver1 > ver2  return True"
        # print "--test", verMin, verMax
        # if len(verMin) < len(verMax): # 如果 verMin 长度 小于 verMax  返回 Ture ,假设成立
        #     return True
        # if len(verMin) > len(verMax):  # 如果 verMin 长度 大于 verMax  返回 False,假设不成立
        #     return False
        #
        # for i in range(len(verMin)):
        #     if int(verMin[i]) ==  int(verMax[i]):
        #         continue
        #     if int(verMin[i]) < int(verMax[i]):
        #         print "---", verMin[i], "<", verMax[i]
        #         return True
        #     else:
        #         return False
        # return False

        # modified by wangshigang
        # if verMin < verMax: return True # else: return False
        LogRecord.instance().logger.info(str(verMin)+"  "+str(verMax))
        lenMax=len(verMax)
        lenMin=len(verMin)

        if lenMin < lenMax:
            verLength=lenMin
        else:
            verLength=lenMax

        for i in range(verLength):
            if int(verMin[i]) < int(verMax[i]):
                return True
            elif int(verMin[i]) > int(verMax[i]):
                return False
            else:
                continue

        if lenMin < lenMax:
            return True
        else:
            return False


    def checkUpgrade(self):
        return self.requestVersion()

    def upgrade(self):
        import socket
        s = None
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # 建立连接:
            s.connect(('127.0.0.1', 9998))
            # 接收欢迎消息:
            # print s.recv(1024)
            print "client send upgrade cmd"
            s.send("upgrade")
        except Exception as e:
            print "upgrade socket err :", e.message
        finally:
            # s.send('exit')
            s.close()


if __name__ == "__main__":


    #  [4, 4, 0, 20160510] [4, 5, 0, 20160603]
    # --test [4, 4, 2, 20160654] [4, 5, 0, 20160603]

    minVersion =  [4, 4, 2, 20160654]
    maxVersion= [4, 4, 0, 20160510]
    curVersion = [4, 5, 0, 20160603]


    upgread = CheckUpgrade(None,None)
    if upgread.compareLessVesion(minVersion,curVersion):
        print minVersion, "<", curVersion
    else:
        print minVersion, ">=", curVersion

    if upgread.compareLessVesion(minVersion,minVersion):
        print minVersion, "<", minVersion
    else:
        print minVersion, ">=", minVersion

    if upgread.compareLessVesion(curVersion,minVersion):
        print curVersion, "<", minVersion
    else:
        print curVersion, ">=", minVersion
