# !/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.business.param_util import ParamUtil
from utils.business.manageone_cmdb_util import ManageOneCmdbUtil
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant


class StorageCMDBUtil:
    def __init__(self, project_id, pod_id, region_id=None):
        self.project_id = project_id
        self.pod_id = pod_id
        self.param_util = ParamUtil()
        self.region_id = region_id
        if not self.region_id:
            self.region_id = self.param_util.get_param_value(
                self.pod_id, DeployConstant.CLOUD_SERVICE_NAME, 'region0_id')
        self.mo_cmdb = ManageOneCmdbUtil(self.project_id, self.pod_id)
        self.cmdb_infos = self.mo_cmdb.get_cloud_service_info(self.region_id,
                                                              index_name=DeployConstant.CLOUD_SERVICE_INDEX)

    @classmethod
    def _extract_bmc_ip(cls, extend_infos):
        ret = []
        for info in extend_infos:
            if info.get("key") == "deploy_bmc_node":
                bmc_ips_list = info.get("value").split(";")
                ret.extend(bmc_ips_list)
        return ret

    def get_deployed_bmc_ip_list(self):
        deployed_bmc_ip_list = []
        for cloud_info in self.get_cloud_service_info():
            extend_infos = cloud_info.get("extendInfos", [])
            deployed_bmc_ip_list.extend(self._extract_bmc_ip(extend_infos))
        return deployed_bmc_ip_list

    def get_deployed_bmc_ip_list_by_name(self, name):
        cloud_info = self.get_cloud_service_info_by_name(name)
        extend_infos = cloud_info.get("extendInfos", [])
        return self._extract_bmc_ip(extend_infos)

    def get_cloud_service_info_by_name(self, name):
        ret = {}
        logger.info("region_id:{}, cloud_service_info:{}".format(self.region_id, self.cmdb_infos))
        for cmdb_info in self.get_cloud_service_info():
            if cmdb_info.get("name") == name:
                ret = cmdb_info
                break
        logger.info("name:{}, cloud service info:{}".format(name, ret))
        return ret

    def get_cloud_service_info(self):
        return self.cmdb_infos

    def get_az_id(self, name):
        ret = ""
        cloud_info = self.get_cloud_service_info_by_name(name)
        if not cloud_info:
            ret = self.param_util.get_param_value(self.pod_id, "OpenStack", 'openstack_region')
            return ret
        extend_infos = cloud_info.get("extendInfos", [])
        for info in extend_infos:
            if info.get("key") == "az_id":
                ret = info.get("value")
                break
        if not ret:
            ret = self.param_util.get_param_value(self.pod_id, "OpenStack", 'openstack_region')
        return ret

    def get_fsm_hostname_list(self, name, fsm_ip_list):
        """只适用于升级更新CMDB的接口

        背景：升级使用V2接口，整改为V3接口，如果CMDB中信息还是V2接口，则无法从CMDB获取到FSM主机名。
             无法获取时使用默认的主机名：["FSM01", "FSM02"]
        """
        default_ret = ["FSM01", "FSM02"]
        ret = []

        def _get_fsm_hostname_from_deploy_node_info():
            deploy_node_infos_list = self.mo_cmdb.get_deploy_node_info(self.region_id)
            logger.info("deploy_node_infos_list:{}".format(deploy_node_infos_list))
            for node_info in deploy_node_infos_list:
                mgmt_ip = node_info.get("mgmtIp")
                if mgmt_ip in fsm_ip_list:
                    ret.append(node_info.get("name"))
            return ret

        if _get_fsm_hostname_from_deploy_node_info():
            logger.info("fsm_hostname_list:{}".format(ret))
            return ret

        cmdb_infos = self.mo_cmdb.get_cloud_service_info_v3(
            self.region_id, index_name=DeployConstant.CLOUD_SERVICE_INDEX)
        cur_cloud_info = {}
        logger.info("region_id:{}, cloud_service_info:{}".format(self.region_id, cmdb_infos))
        for cmdb_info in cmdb_infos:
            if cmdb_info.get("name") == name:
                cur_cloud_info = cmdb_info
                break
        logger.info("name:{}, cloud service info:{}".format(name, cur_cloud_info))
        if not cur_cloud_info or not cur_cloud_info.get("services"):
            return default_ret

        service_info = cur_cloud_info.get("services")
        components = service_info[0].get("components")
        for info in components:
            if info.get("indexName") == "FSM":
                ret = info.get("nodeNames")
                break
        return ret
