#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import utils.common.log as logger
from utils.DBAdapter.DBConnector import BaseOps
from utils.common.message import Message
from utils.common.exception import HCCIException
from utils.common.fic_base import StepBaseInterface
from utils.business.param_util import ParamUtil
from utils.business.manageone_cmdb_util import ManageOneCmdbUtil
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.logic.vm_operate import VMOperate
from plugins.DistributedStorage.utils.common.query_for_cmdb import DealInfoForCMDB
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant
from plugins.DistributedStorage.utils.interface.DistributedStorage import DistributedStorageArgs

logger.init("Mnagae FusionsStorage800 RegisterCMDB")


class FSB8RegisterCMDB(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(FSB8RegisterCMDB, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()
        self.service_name = 'DistributedStorageManage'
        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, self.service_name, 'region0_id')
        self.storage_tool = DistributedStorageArgs(self.project_id, self.pod_id)
        self.modify_ha_boolean = get_project_condition_boolean(project_id, "ProjectModifactionRegionConHA")

    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类对象
        """
        self.rollback(project_id, pod_id)
        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.set_cmdb_info(project_id, pod_id)
            return Message(200)
        except HCCIException as e:
            logger.error(e)
            return Message(500, e)
        except Exception as e:
            logger.error(e)
            return Message(500, HCCIException("626267", str(e)))

    def set_cmdb_info(self, project_id, pod_id):
        """
        管理存储微服务分为FSM和FSA。FSM拓扑视图下包含主备虚拟机，管理节点fsa由openstack管理,不添加微服务
        """
        logger.info("start to set FSB800 cmdb info.")
        # 构造云服务信息
        if get_project_condition_boolean(self.project_id, 'ManageStorFB80'):
            deployment_type = "converge"
        else:
            deployment_type = "separate"
        # 启用需要添加两套，未启用只需要添加一套，逻辑一样，但是float_ip key不一样
        # FSMOMFloatingIP, HAFSMOMFloatingIP
        portal_pwd = self.storage_tool.get_default_fsm_portal_pwd()
        float_ip = self.param_util.get_param_value(self.pod_id, self.service_name, 'FSMOMFloatingIP')
        float_ip_list = [{'float_ip': float_ip, 'az_id': 'manage-az', 'dm_update_pwd': portal_pwd}]
        if get_project_condition_boolean(self.project_id, "RegionConHA"):
            ha_float_ip = self.param_util.get_param_value(self.pod_id, self.service_name, 'HAFSMOMFloatingIP')
            float_ip_dict = {'float_ip': ha_float_ip, 'az_id': 'dr-manage-az', 'dm_update_pwd': portal_pwd}
            float_ip_list.append(float_ip_dict)
        if self.modify_ha_boolean:
            ha_float_ip = self.param_util.get_param_value(self.pod_id, self.service_name, 'HAFSMOMFloatingIP')
            float_ip_dict = {'float_ip': ha_float_ip, 'az_id': 'dr-manage-az', 'dm_update_pwd': portal_pwd}
            float_ip_list = [float_ip_dict]
        logger.info("get manage storage float ip list success")
        for float_dic in float_ip_list:
            az_id = float_dic.get("az_id")
            cloud_service = self.assemble_cloud_service_info(float_dic, deployment_type)
            if not cloud_service:
                continue
            # 设置云服务信息
            mo_cmdb = ManageOneCmdbUtil(self.project_id, self.pod_id)
            mo_cmdb.set_cloud_service_info_v3(self.region_code, cloud_service)
            logger.info("current az_id :%s.set DistributedStorage cmdb info successfully!" % az_id)

    def assemble_cloud_service_info(self, float_dic, deployment_type):
        """
        生成注册cmdb信息
        """
        cloud_service = None
        float_ip = float_dic.get('float_ip')
        if not float_ip:
            return cloud_service
        deal_tool = DealInfoForCMDB(self.project_id, self.pod_id, float_dic)
        deal_tool.tool_login()
        az_id = float_dic.get('az_id')
        deploy_node_infos, fsm_list = deal_tool.get_node_info()
        master_fsm, standby_fsm = self.vm_operate.get_vm_data(self.pod_id, float_ip)
        if self.modify_ha_boolean:
            fsm_node_info = deal_tool.get_fsm_node_info(master_fsm, standby_fsm)
            deploy_node_infos.extend(fsm_node_info)
        vm_hostnames = [master_fsm.get('hostname'), standby_fsm.get('hostname')]

        version = deal_tool.get_version()
        service_info = deal_tool.get_services_info(version, self.region_code, [], 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": deployment_type},
                {"key": "fsm_float_ip", "value": float_ip},
                {"key": "fsm_primary_ip", "value": fsm_list[0]},
                {"key": "fsm_slave_ip", "value": fsm_list[1]},
            ],
            "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))
        deal_tool.tool_logout()
        return cloud_service
