# -*- coding: UTF-8 -*-
from hotpatch import SysResourceCheck
from hotpatch import PatchCheck
from hotpatch import NdmpClientConnectCheck
from hotpatch import ISFrontBandWidthEnough
from hotpatch import DiskUsageCheck
from aslpatch import ExtLunSingleLinkCheck
from aslpatch import ISDoubleCtrlCheck
from aslpatch import ISSameVersionCheck
from aslpatch import SysAlarmCheck
from aslpatch import SysFaultCheck
from common.constant import PATCH_TYPE
from common import resourceParse
from common.baseFactory import log, threadUp, finishProcess
from checkitems import DaemonProcessCheck
from checkitems import check_single_controller_free_memory
from checkitems import check_message_connection_number
from checkitems import check_systemdisk_risk

from cbb.business.checkitems.IgnoreCheck4Patch import ignore_precheck, \
    check_result

totalRemainTime = 16


@ignore_precheck
def execute(dataDict):
    context = dataDict.get("context")
    lang = dataDict.get('lang')
    resource = resourceParse.execute(lang)
    dataDict["resource"] = resource
    deviceSN = str(dataDict.get('dev').getDeviceSerialNumber())
    patchType = context.get("patchType_%s"%deviceSN)
    log.info(dataDict,"patchType:==============="+patchType)
    threadUp(dataDict, "precheck", totalRemainTime)

    try:
        msg_list = list()
        if patchType == PATCH_TYPE.HOT_PATCH:
            hotpatch_check(dataDict, msg_list)
        elif patchType == PATCH_TYPE.ASL_PATCH:
            aslpatch_check(dataDict, msg_list)
        else:
            log.error(dataDict,u'获取补丁包类型异常   PATCH_TYPE:' +patchType)
            err_msg = resource.get('upload.pkgTypeAbnormality')
            msg_list.append(err_msg)

        if not msg_list:
            return True, "", None
        log.info(dataDict, "patch precheck is not pass.")
        return False, "\n".join(msg_list), None
    finally:
        finishProcess(dataDict, "precheck")


def hotpatch_check(data_dict, msg_list):
    # PatchCheck放在第一个，会删除内存中的补丁，位置不可移动
    check_item_list = (PatchCheck, SysResourceCheck, NdmpClientConnectCheck,
                       ISFrontBandWidthEnough, DiskUsageCheck,
                       DaemonProcessCheck, check_single_controller_free_memory,
                       check_message_connection_number,
                       check_systemdisk_risk)
    for check_item in check_item_list:
        check_result(check_item.execute(data_dict), msg_list)


def aslpatch_check(data_dict, msg_list):
    check_res = ExtLunSingleLinkCheck.execute(data_dict)
    check_result(check_res, msg_list)
    check_res = SysAlarmCheck.execute(data_dict)
    check_result(check_res, msg_list)
    check_res = SysFaultCheck.execute(data_dict)
    check_result(check_res, msg_list)
    check_res = ISSameVersionCheck.execute(data_dict)
    check_result(check_res, msg_list)
