# -*- 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.business.manageone_cmdb_util import ManageOneCmdbUtil
from plugins.DistributedStorage.common.base import TestCase
from plugins.DistributedStorage.utils.common.query_for_cmdb import DealInfoForCMDB, DistributedStorageRegCMDBBase
from plugins.DistributedStorage.utils.iterm.storage_cmdb_util import StorageCMDBUtil
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant, DeployType


class UpdateCMDB(TestCase, DistributedStorageRegCMDBBase):
    def __init__(self, project_id, pod_id, regionid_list, fs_args, **kwargs):
        super(UpdateCMDB, self).__init__(project_id, pod_id)
        self.more_args = kwargs
        self.project_id = project_id
        self.pod_id = pod_id
        self.region_id = regionid_list[0]
        self.float_ip = fs_args.get('float_ip')
        self.dm_login_args = {'float_ip': self.float_ip, 'dm_update_pwd': fs_args["password"]}
        self.fs_cmdb_util = StorageCMDBUtil(self.project_id, self.pod_id, self.region_id)

    def procedure(self):
        logger.info('Start update CMDB.')
        try:
            self.main()
        except HCCIException as err:
            logger.error('update CMDB failed:{}'.format(err))
            logger.error(traceback.format_exc())
            raise err
        except Exception as err:
            logger.error('update CMDB failed:{}'.format(err))
            logger.error(traceback.format_exc())
            raise HCCIException(620008, str(err)) from err
        return Message(200)

    def main(self):
        cloud_service_info = self.get_cloud_service_info()
        mo_cmdb = ManageOneCmdbUtil(self.project_id)
        mo_cmdb.set_cloud_service_info_v3(self.region_id, cloud_service_info)
        logger.info("End to set cloud info into CMDB.")

    def get_cloud_service_info(self):
        """
        生成V3接口注册cmdb的信息
        """
        deploy_node_infos, fsm_ip_list, name, version, osd_hostname_list = self.get_info_from_dm(self.dm_login_args)
        vm_hostname_list = self.get_fsm_vm_hostname_list(name, fsm_ip_list)
        cloud_service_info = {
            "indexName": DeployConstant.CLOUD_SERVICE_INDEX,
            "version": version,
            "name": name,
            "extendInfos": [
                {'key': "az_id", "value": self.get_az_id(name)},
                {"key": "fsm_float_ip", "value": self.dm_login_args.get("float_ip")},
                {"key": "fsm_primary_ip", "value": fsm_ip_list[0]},
                {"key": "fsm_slave_ip", "value": fsm_ip_list[1]},
            ],
            "deployNodeInfos": deploy_node_infos,
        }

        deploy_type = self.get_deploy_type()
        if deploy_type == DeployType.SEPARATE:
            cloud_service_info.get("extendInfos").append(
                {"key": "deploy_bmc_node", "value": ";".join(self.get_all_bmc_ip(name))}
            )
            services = DealInfoForCMDB.get_services_info(version, self.region_id, osd_hostname_list, vm_hostname_list)
        else:
            services = DealInfoForCMDB.get_services_info(version, self.region_id, [], vm_hostname_list)
        cloud_service_info.get("extendInfos").append({'key': "deployment_type", "value": deploy_type})
        cloud_service_info["services"] = services

        logger.info("get param cloud_service: %s" % str(cloud_service_info))
        return cloud_service_info

    def get_all_bmc_ip(self, name):
        bmc_ip_list = self.fs_cmdb_util.get_deployed_bmc_ip_list_by_name(name)
        logger.info("bmc_ip_list:{}".format(bmc_ip_list))
        return sorted(set(bmc_ip_list))

    def get_az_id(self, name):
        az_id = self.fs_cmdb_util.get_az_id(name)
        logger.info("az_id:{}".format(az_id))
        return az_id

    def get_deploy_type(self):
        deal_tool = DealInfoForCMDB(self.project_id, self.pod_id, self.dm_login_args)
        deal_tool.tool_login()
        try:
            deploy_type = deal_tool.get_deploy_type()
        finally:
            deal_tool.tool_logout()
        logger.info("deploy_type:{}".format(deploy_type))
        return deploy_type

    def get_fsm_vm_hostname_list(self, name, fsm_ip_list):
        fsm_vm_hostname_list = self.fs_cmdb_util.get_fsm_hostname_list(name, fsm_ip_list)
        logger.info("fsm_vm_hostname_list:{}".format(fsm_vm_hostname_list))
        return fsm_vm_hostname_list
