#  coding=UTF-8
#  Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved.

import os

from com.huawei.ism.tlv.bean import Param
from com.huawei.ism.tool.framework.platform.util import ApplicationContext
from com.huawei.ism.tlv.docoder import ParamType
from com.huawei.ism.tlv import TLVUtils
from com.huawei.ism.tool.protocol.tlv.cmds import CommandConstans
from com.huawei.ism.tlv.lang import UnsignedInt32
from cbb.frame.tlv import tlvUtil
from cbb.frame.tlv import tlvData
from cbb.frame.ruleConfig import common
from cbb.frame.cli import cliUtil

from cbb.frame.base import baseUtil

from resource.resource import MESSAGES_DICT


def upload_timeout_callback(data_dict, hot_patch_pkg_name):
    """
    上传补丁包超时回调函数
    :param data_dict: 上下文
    :param hot_patch_pkg_name: 补丁包路径
    :return: 超时返回错误消息
    """
    lang = data_dict.get("lang")
    error_key = "upload.patch.pkg.timeout"
    err_msg = baseUtil.getPyResource(
        lang, error_key, "", resource=MESSAGES_DICT
    )
    return False, err_msg


def execute_tlv(data_dict, command, location_id):
    """
    执行 tlv 命令
    :param data_dict: 上下文
    :param command: tlv 命令
    :param location_id:
    :return:
    """
    cmd_default_time_out = 60 * 5
    tlv_con = data_dict.get("tlv")
    params = TLVUtils.paramList(
        Param(0, ParamType.UNSIGN_INT, UnsignedInt32(0)),
        Param(1, ParamType.STRING, ""),
        Param(2, ParamType.UNSIGN_INT, UnsignedInt32(0)),
        Param(3, ParamType.STRING, ""),
        Param(4, ParamType.STRING, ""),
        Param(5, ParamType.STRING, ""),
        Param(6, ParamType.STRING, ""),
        Param(7, ParamType.STRING, ""),
        Param(8, ParamType.STRING, ""),
        Param(9, ParamType.STRING, ""),
        Param(12, ParamType.STRING, command),
        Param(13, ParamType.UNSIGN_INT, UnsignedInt32(location_id)),
    )
    recs = tlv_con.getBatch(
        CommandConstans.EXC_UPD, params, cmd_default_time_out
    )
    return recs


def check_recs_by_rest(item_dict, recs, error_msg_list, lang):
    """
    通过rest获取数据

    :param item_dict: 数据集合
    :param recs: 命令
    :param error_msg_list: 错误消息集合
    :param lang: 语言
    :return:
    """
    flag = True
    for record in recs:
        result = tlvUtil.getRecordValue(
            record, tlvData.CMO_UPD_EXECUTE_DEFINE["RESULT"]
        )
        nodeId = tlvUtil.getRecordValue(
            record, tlvData.CMO_UPD_EXECUTE_DEFINE["NODE_ID"]
        )
        # 根据模块返回值获取对应的字典值,如果失败返回None
        itemVal = item_dict.get(result, None)
        if itemVal is None:
            error_msg_list.append(common.getMsg(lang, "query.result.abnormal"))
            flag = False
            continue
        status = itemVal.get("status", None)
        if status is True:
            continue
        flag = False
        error_msg_list.append(common.getMsg(lang, itemVal["msg"], nodeId))
    return flag


def check_recs_by_tlv(data_dict, cmd, error_msg_list, log, item_dict):
    """
    通过tlv获取数据

    :param data_dict: 数据集合
    :param cmd: 命令
    :param error_msg_list: 错误消息集合
    :param log: 日志
    :return:
    """
    lang = data_dict.get("lang")
    recs = execute_tlv(data_dict, cmd, 2)
    if not recs:
        log.error("[check_recs_by_tlv]records is none")
        msg = cliUtil.getMsg(lang, "query.result.abnormal")
        error_msg_list.append(msg)
        return False
    log.logInfo("records={}".format(recs))
    err_msg = list()
    for rec in recs:
        node_id = rec.getParamStrValue(0)
        result = rec.getParamStrValue(1)
        if result == "TimeOut":
            err_msg.append(
                cliUtil.getMsg(
                    lang, "execution command timed out", (node_id, cmd)
                )
            )
            continue
        itemVal = item_dict.get(result, None)
        if not itemVal:
            msg = cliUtil.getMsg(lang, "query.result.abnormal")
            error_msg_list.append(msg)
            return False
        status = itemVal.get("status", None)
        if status is True:
            continue
        err_msg.append(common.getMsg(lang, itemVal["msg"], node_id))
        log.logWarning(
            "cmd :{}, node ：{} check recs by tlv not pass".format(cmd, node_id)
        )
    error_msg_list.extend(err_msg)
    return len(err_msg) == 0


def check_system_type_version(product_model, product_version):
    """
    涉及产品版本及型号判断,
     V3R3C20 V3R5C00/C01 V3R6 V5R7C00~V5R7C61 Dorado V3
    :param product_model: 型号
    :param product_version: 版本
    :return: 是否涉及T,F
    """
    model = product_model.lower()
    version = product_version.upper()

    # dorado V3
    if 'dorado' in model and version.startswith('V3'):
        return True
    # V3
    if any([version.startswith('V300R003C20'), version.startswith('V300R005C00'), version.startswith('V300R005C01'),
            version.startswith('V300R006')]):
        return True
    # V5R7C00~V5R7C61
    if version.startswith('V500R007'):
        return True
    return False


def get_auth_package_path():
    return ApplicationContext.getInstance().getWorkPath() + os.path.sep + "configuration" + os.path.sep + "test_sys_disk.tgz"
