# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import utils.common.log as logger
from utils.common.message import Message
from utils.common.exception import FCDException
from utils.DBAdapter.DBConnector import BaseOps
from utils.business.param_util import ParamUtil
from utils.common.fic_base import StepBaseInterface
from utils.business.manageone_cmdb_util import ManageOneCmdbUtil
from plugins.DistributedStorage.scripts.logic.vm_operate import VMOperate
from plugins.DistributedStorage.scripts.logic.InstallOperate import InstallOperate
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorage.scripts.utils.common.query_for_cmdb import DealInfoForCMDB
from plugins.DistributedStorageReplication.scripts.common_utils.config_params import Params


class FSB8RegisterCMDB(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()
        self.param_util = ParamUtil()
        self.vm_operate = VMOperate(self.project_id, self.pod_id, None)
        self.region_code = self.param_util.get_param_value(self.pod_id, 'DistributedStorageBusiness', 'region0_id')
        parameters = Params(self.project_id, self.pod_id, "FusionStorageBlockReplication")
        self.fs_args = parameters.get_rep_fsa_params()
        self.install_opr = InstallOperate(self.project_id, self.pod_id, self.fs_args)
        super(FSB8RegisterCMDB, self).__init__(project_id, pod_id)

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：执行安装前的资源预检查，该接口由execute接口调用，工具框架不会直接调用此接口。
        :param project_id:
        :param pod_id:
        :return:
        """
        return Message(200)

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

    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(200)

    def execute(self, project_id, pod_id):
        """
        标准调用接口：执行安装前预检查&安装&配置
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        try:
            self.procedure(project_id, pod_id)
            return Message(200)
        except FCDException as e:
            logger.error(e)
            return Message(500, e)
        except Exception as e:
            logger.error(e)
            return Message(500, FCDException("626267", str(e)))

    def procedure(self, project_id, pod_id):
        """
        业务存储微服务分为FSM和FSA。FSM拓扑视图下包含主备虚拟机，FSA拓扑视图下包含复制节点
        """
        logger.info("start to set FSB800 cmdb info.")
        # 构造云服务信息
        float_ip = self.fs_args.get('float_ip')
        if not float_ip:
            return
        logger.info("rep float ip: %s." % str(float_ip))

        deal_tool = DealInfoForCMDB(project_id, pod_id, self.fs_args)
        deal_tool.tool_login()
        az_id = self.install_opr.get_az_id('DistributedStorageBusiness')
        deploy_node_infos, fsm_list = deal_tool.get_node_info()
        rep_nodes_info = self.db.get_install_os_list_info(pod_id, 'rep')
        rep_nodes_list = [node.get("bmc_ip") for node in rep_nodes_info]
        rep_host_names = [node.get("hostname") for node in rep_nodes_info]
        master_fsm, standby_fsm = self.vm_operate.get_vm_data(self.pod_id, float_ip)
        vm_hostnames = [master_fsm.get('hostname'), standby_fsm.get('hostname')]
        deployed_bmc_ips = ";".join(rep_nodes_list)
        version = deal_tool.get_version()
        service_info = deal_tool.get_services_info(version, self.region_code, rep_host_names, vm_hostnames)
        cloud_service = {
            "indexName": DeployConstant.CLOUD_SERVICE_INDEX,
            "version": version,
            "name": deal_tool.get_name(),
            "extendInfos": [
                {'key': "az_id", "value": az_id},
                {'key': "deployment_type", "value": "separate"},
                {"key": "fsm_float_ip", "value": float_ip},
                {"key": "fsm_primary_ip", "value": fsm_list[0]},
                {"key": "fsm_slave_ip", "value": fsm_list[1]},
                {"key": "deploy_bmc_node", "value": deployed_bmc_ips}
            ],
            "deployNodeInfos": deploy_node_infos,
            "services": service_info
        }
        logger.info("get param cloud_service: %s" % str(cloud_service))
        logger.info("get param region_id: %s" % str(self.region_code))
        # 设置云服务信息
        mo_cmdb = ManageOneCmdbUtil(self.project_id, self.pod_id)
        mo_cmdb.set_cloud_service_info_v3(self.region_code, cloud_service)
        deal_tool.tool_logout()
        logger.info("current az_id :%s.set DistributedStorage cmdb rep cluster info successfully!" % az_id)
