# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback

import utils.common.log as logger
from utils.common.message import Message
from utils.common.exception import HCCIException
from utils.common.fic_base import StepBaseInterface
from utils.DBAdapter.DBConnector import BaseOps
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.logic.deploy_operate import DeployOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant
from plugins.DistributedStorage.utils.interface.DistributedStorage import DistributedStorageTool


class CheckDistributedStorageUpgradeStatusInf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super().__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：
        :param project_id:
        :param pod_id:
        :return:
        """
        return Message()

    def execute(self, project_id, pod_id):
        """
        标准调用接口：
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        try:
            CheckDistributedStorageUpgradeStatusImpl(project_id, pod_id).procedure()
        except HCCIException as e1:
            return Message(500, e1)
        except Exception as e2:
            err_msg = traceback.format_exc()
            logger.error('ERROR: {}, details: {}'.format(e2, err_msg))
            return Message(500, HCCIException(627207, err_msg))
        return Message(200)

    def rollback(self, project_id, pod_id):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message()

    def retry(self, project_id, pod_id):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(project_id, pod_id)

    def check(self, project_id, pod_id):
        """
        标准调用接口：重试
        :param project_id:
        :param pod_id:
        :return:
        """
        return Message()


class CheckDistributedStorageUpgradeStatusImpl:
    """检查存储集群是否处于升级状态，升级状态不支持扩容，检查不通过。

    deploy manager 自升级过程中，查询升级状态接口不能用的，工步失败，给出排查建议
    """
    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()
        self.storage_tool = DistributedStorageTool(self.project_id, self.pod_id, self.db)

    @classmethod
    def _check_upgrade_status(cls, opr: DeployOperate):
        result, data = opr.get_upgrade_status()
        current_phase = data.get("currentPhase")
        logger.info("Rest result:{}, upgrade status: {}".format(result, current_phase))
        if current_phase != "":
            raise HCCIException(627625, current_phase)

    def procedure(self):
        logger.info('Start to check')

        fsm_args_lst = self.storage_tool.get_storage_float_ip()
        if get_project_condition_boolean(self.project_id,
                                         "!DRStorage_TFB_PD&DRStorage_TFB_Sep&(CSDRStorage_TFB|CSHAStorage_TFB)"):
            logger.info('Querying DR Site Login Information')
            disaster_float_ip = self.db.get_user_input_cloud_param_by_key(
                self.project_id, "disaster_tolerant_storage_fsm_ip")
            fsm_args_lst = list(filter(lambda x: x.get("float_ip") == disaster_float_ip, fsm_args_lst))

        if not fsm_args_lst:
            err_msg = 'Failed to query the DeviceManager login information from LLD'
            logger.error(err_msg)
            raise HCCIException(627622, err_msg)

        logger.info('Checking the Upgrade Status of the DistributedStorage Cluster')
        for fsm_args in fsm_args_lst:
            float_ip = fsm_args.get("float_ip")
            logger.info("Current floatIP:{}".format(float_ip))
            opr = DeployOperate(float_ip=float_ip)
            opr.login(DeployConstant.DM_LOGIN_USER, fsm_args.get("portal_pwd"))
            logger.info("check DistributedStorage Software status")
            try:
                self._check_upgrade_status(opr)
            finally:
                opr.logout()

        logger.info("Finish, pass")
