# -*- coding: UTF-8 -*-

import java.lang.Exception as JException
from com.huawei.ism.tool.obase.exception import PwdCLIOverrunException

from common.constant import PATCH_TYPE
from common import resourceParse
from common.baseFactory import log, deleteTempPatch
from common import checkUtils
from common.checkUtils import CheckItemObserver
from checkitems import (
    service_netlog_ex_enable_check,
    memory_leakage_check,
    stop_power_patch_upgrade
)

from cbb.business.checkitems.SystemInnerCheck import UpgradeCheck

# 创建SSH连接失败信息
SSH_CONNECT_ERROR_MSG = "'NoneType' object has no attribute 'getCli'"


def execute(dataDict):
    lang = dataDict.get('lang')
    resource = resourceParse.execute(lang)
    try:
        deviceSN = str(dataDict.get('dev').getDeviceSerialNumber())
        context = dataDict.get("context")
        patchType = context.get("patchType_%s" % deviceSN)
        log.info(dataDict, "deviceSN=%s, patchType:===============%s" % (deviceSN, patchType))
        checkObserver = CheckItemObserver(dataDict, "postcheck")

        if patchType == PATCH_TYPE.HOT_PATCH:
            checkType = "HotpatchVerify"
            log.info(dataDict, "[PreCheck]user setted checkType is{}".format(
                checkType))
            flowchoiceNum = dataDict.get('flowchoice')
            dataDict.update(checkType=checkType, flowchoice=flowchoiceNum, observer=checkObserver)

            preCheck = UpgradeCheck(dataDict)
            checkResult = preCheck.execute()
            if not checkResult[0]:
                return (False, checkResult[1], "")
            error_message_list = []
            if not checkObserver.isAllSystemInnerItemsPassed():
                error_message_list.append(checkUtils.getNotPassedItemsMsg(checkObserver.getAllCheckItems()))
            post_check_local(dataDict, error_message_list)
            if error_message_list:
                return False, "".join(error_message_list), ""
            return True, '', None
        elif patchType == PATCH_TYPE.ASL_PATCH:
            return True, '', None
        else:
            log.error(dataDict, u'Failed to obtain the patch package type.   PATCH_TYPE:{}'.format(patchType))
            return False, resource.get('upload.pkgTypeAbnormality'), None
    except PwdCLIOverrunException as pwd_cli_over_exception:
        log.error(dataDict,
                  u'Remaining memory is less than 130 MB, or the CLI reaches limit：{}'.format(pwd_cli_over_exception))
        return False, resource.get('upgrade.error.cli.over.run'), None
    except (JException, Exception) as e:
        log.error(dataDict, u'An exception occurs during the pre-patch check.：{}'.format(e))
        if SSH_CONNECT_ERROR_MSG in str(e):
            return False, resource.get("upgrade.error.cli.connect.failed"), None
        return False, resource.get('upgrade.postcheck.notpassed'), None
    finally:
        deleteTempPatch(dataDict)


def post_check_local(data_dict, error_message_list):
    """
    增加post check 本地检查项
    :param data_dict:
    :param error_message_list:
    :return:
    """
    flag, msg, __ = stop_power_patch_upgrade.execute(data_dict)
    if not flag:
        error_message_list.append(msg)

    flag, msg, __ = service_netlog_ex_enable_check.execute(data_dict)
    if not flag:
        error_message_list.append(msg)

    flag, msg, __ = memory_leakage_check.execute(data_dict)
    if not flag:
        error_message_list.append(msg)
