# -*- coding: UTF-8 -*-
from cbb.frame.cli import cliUtil
from cbb.frame.ruleConfig import common
from cbb.frame.context import contextUtil
from cbb.frame.tlv import tlvUtil
from cbb.frame.tlv import tlvData
from checkitems.evaluate_pre_check import link_pre_check
from java.lang import Exception as JException
import traceback
from service.func_utils import check_recs_by_rest
from service.func_utils import check_recs_by_tlv


def execute(data_dict):
    """
    主程序入口，java框架调用

    :param data_dict: 上下文
    :return:
    """
    # 执行升级前检查
    flag, err_msg, cli_ret = link_pre_check(data_dict)
    if flag:
        return flag, err_msg, cli_ret

    lun_link_status = TlvServiceExtLunLinkStatus(data_dict)
    # 如果空闲内存不足，清理缓存后再检查

    flag = lun_link_status.check_lun_link_status()
    return (
        flag,
        "\n".join(lun_link_status.error_msg_list),
        "\n".join(lun_link_status.all_ret_list),
    )


class TlvServiceExtLunLinkStatus:
    def __init__(self, data_dict):
        """
        初始化
        :param data_dict: 上下文
        """
        self.all_ret_list = list()
        self.error_msg_list = list()
        self.data_dict = data_dict
        self.log = common.getLogger(contextUtil.getLogger(data_dict), __file__)
        self.lang = data_dict.get("lang")

    def check_lun_link_status(self):
        try:
            # 获取cli回显
            flag = True
            tlv = contextUtil.getTlv(self.data_dict)
            checkItem = "CHECK_SERVICE_EXTLUN_LINKSTATUS"
            item_dict = tlvData.UPD_CHECK_RESULT[checkItem]
            self.log.logExecCmd(checkItem)
            try:
                # 根据检查项获取配置字典值 新版本适用
                recs = tlvUtil.get_upgrade_records(tlv, checkItem)
                self.log.logInfo("records={}".format(recs))
                return check_recs_by_rest(
                    item_dict, recs, self.error_msg_list, self.lang
                )
            except (JException, Exception) as e:
                self.log.logException(e)
                self.log.logError(
                    "sys isalldoublectrl.. by rest except:{}. use tlv".format(
                        traceback.format_exc()
                    )
                )
                # 命令层名兼容rest和tlv。当老版本不支持rest时，使用tlv。
                if e.args and "-1" in str(e.args[0]):
                    cmd = "ld checkextlunsinglelink"
                    return check_recs_by_tlv(
                        self.data_dict,
                        cmd,
                        self.error_msg_list,
                        self.log,
                        item_dict,
                    )
            return flag
        except (JException, Exception) as exception:
            self.log.logException(exception)
            self.error_msg_list.append(
                common.getMsg(self.lang, "query.result.abnormal")
            )
            return False
        finally:
            try:
                cli = contextUtil.getCli(self.data_dict)
                cmd = "show remote_lun single_link"
                checkRet = cliUtil.excuteCmdInDeveloperMode(
                    cli, cmd, True, self.lang
                )
                self.all_ret_list.append(checkRet[1])
            except (JException, Exception) as e:
                self.log.logException(e)
