# -*- coding: UTF-8 -*-
from com.huawei.ism.tlv.lang import UnsignedInt32
from com.huawei.ism.tlv.bean import Param
from com.huawei.ism.tlv.docoder import ParamType
from com.huawei.ism.tlv.bean import Record
from com.huawei.ism.tlv import TLVUtils
from com.huawei.ism.tool.protocol.tlv.cmds import CommandConstans
from com.huawei.ism.tool.protocol.tlv.cmds.CommandConstans import UpgradeStatus
from cbb.frame.tlv.tlvUtil import delete_packages
from cbb.frame.util.common import is_cold_patch
from service.patch_multi_service import PatchMultiPackagesManager
from common.baseFactory import *
from common import resourceParse 
from common.baseFactory import log
import re


def execute(dataDict):
    try:
        # 执行升级前检查
        return preCheck(dataDict)
    finally:
        delete_pkg(dataDict)


def delete_pkg(data_dict):
    """
    删除内存补丁
    :param dataDict:
    :return:
    """
    if is_cold_patch(data_dict.get("pkgVersion")):
        return

    hot_patch_path = data_dict['packagePath']
    manager = PatchMultiPackagesManager(data_dict, hot_patch_path)
    if manager.is_multi_patch_package():
        return

    delete_packages(data_dict)
    return


"""
    查询升级检查项，并更新界面
"""
def disposeRecs(recs, dataDict):
    lang = dataDict['lang']
    resource = resourceParse.execute(lang)
    recNum = recs.size()
    flag = True
    upgradeErrMsg = ''
    itemState = True
    for index in range(0, recNum):
        rec = recs.get(index)
        nodeId = rec.getParamStrValue(0)
        result = rec.getParamStrValue(1)
        log.info(dataDict,"SysResourceCheck result:" + result)
        if result == "true":
            #执行成功
            errorKey = "HotPatchCheck.pass"
        elif result == "pkgerror":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.notpass.pkgerror"
        elif result == "versionerror":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.notpass.versionerror"
        elif result == "reinstall":
            #执行失败
            errorKey = "HotPatchCheck.notpass.reinstall.1"
            itemState = False
            flag, reinstallErrMsg = patchErrorKey(dataDict, resource)
            if not flag:
                upgradeErrMsg = reinstallErrMsg
                break
        elif result == "memoryerror":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.notpass.memoryerror"
        elif result == "sysdiskerror":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.notpass.sysdiskerror"
        elif result == "sysbusy":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.notpass.sysbusy"
        elif result == "hotpatcherror":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.notpass.hotpatcherror"
        elif result == "TimeOut":
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.timeout"    
        else:
            #执行失败
            itemState = False
            errorKey = "HotPatchCheck.error"
        upgradeErrMsg += nodeId + '--' + resource.get(errorKey) + '\n'
    if not upgradeErrMsg:
        itemState = False
        upgradeErrMsg = resource.get("HotPatchCheck.error")
    return (itemState, upgradeErrMsg, None)
       

def preCheck(dataDict):
    
        recs = executeCheck(dataDict, "upg hotpachcheck", 2)        
        return disposeRecs(recs,dataDict)


def patchErrorKey(dataDict, resource):

    context = dataDict["context"]
    curHotPatchVersion = context.get("curHotPatchVersion")

    if curHotPatchVersion is None:
        return True, ""

    log.info(dataDict, "hotPatchCurVersion" + curHotPatchVersion)
    sysVersion = re.compile(r'SPH\d9[89]')
    if sysVersion.search(curHotPatchVersion):
        return False, resource.get("HotPatchCheck.notpass.reinstall.2") % (curHotPatchVersion, "=")
    return True, ""