# -*- coding: utf-8 -*-
# -*- 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.DBAdapter.DBConnector import BaseOps
from utils.common.exception import HCCIException
from utils.common.fic_base import StepBaseInterface
from plugins.DistributedStorage.utils.interface.DistributedStorage import DistributedStorageTool
from plugins.DistributedStorage.logic.deploy_operate import DeployOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant


class CheckAddNodeDiskType(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(CheckAddNodeDiskType, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.database = BaseOps()
        self.storage_tool = DistributedStorageTool(self.project_id, self.pod_id, self.database)

    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:
            self.procedure()
        except HCCIException as err:
            logger.error("Check failed:{}".format(err))
            return Message(500, err)
        except Exception as err:
            logger.error(traceback.format_exc())
            return Message(500, err)
        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()

    def procedure(self):
        """
        新增存储节点、新增存储池、扩AZ复用新增存储池：检查存储版本与插件版本是否一致

        """
        bmc_info_list = self.database.get_install_os_list_info(self.pod_id)
        if not bmc_info_list:
            logger.info("No osd node needs to be added to the storage pool.")
            return

        logger.info('step 1 Querying Login Information')
        fsm_args_lst = self.storage_tool.get_storage_float_ip()
        if not fsm_args_lst:
            err_msg = 'Failed to query the DeviceManager login information from LLD'
            logger.error(err_msg)
            raise Exception(err_msg)
        fsm_args = fsm_args_lst[0]

        logger.info("step 2 Querying resource pool information")
        opr = DeployOperate(float_ip=fsm_args.get("float_ip"))
        opr.login(DeployConstant.DM_LOGIN_USER, fsm_args.get("portal_pwd"))
        res_pool = opr.query_storage_pool()
        opr.logout()
        pool_data = res_pool.get_query_data()
        pool_info_list = pool_data.get('storagePools')
        if len(pool_info_list) == 0:
            logger.error('No resource pool information is found.details:{}'.format(pool_data))
            raise Exception("No resource pool information is found.")

        logger.info("step 3 Check Primary Type.")
        checked_pool_list = []
        for bmc_info in bmc_info_list:
            storage_pool_name = bmc_info.get("storage_pool_name_and_slot")
            if storage_pool_name in checked_pool_list:
                continue
            checked_pool_list.append(storage_pool_name)

            primary_type = bmc_info.get("primary_type")
            for pool_info in pool_info_list:
                if pool_info.get("poolName") == storage_pool_name:
                    media_type = pool_info.get("mediaType")
                    msg = f"mediaType of {storage_pool_name} is {DeployConstant.PRODUCT_TO_LLD_MAP.get(media_type)}, " \
                          f"LLD mediaType is {primary_type}"
                    logger.info(msg)
                    if primary_type != DeployConstant.PRODUCT_TO_LLD_MAP.get(media_type):
                        raise HCCIException(626404,
                                            primary_type,
                                            storage_pool_name,
                                            DeployConstant.PRODUCT_TO_LLD_MAP.get(media_type))
                    break

        logger.info("Pass")
