# -*- coding: utf-8 -*-
import traceback

import utils.common.log as logger
from utils.business.manageone_cmdb_util import ManageOneCmdbUtil
from utils.common.message import Message
from utils.common.exception import HCCIException
from plugins.DistributedStorage.common.base import TestCase
from plugins.DistributedStorage.logic.VMOperate import VMOperate
from plugins.DistributedStorage.utils.common.QueryForCMDB import DealInfoForCMDB, DistributedStorageRegCMDBBase
from plugins.DistributedStorage.utils.iterm.storage_cmdb_util import StorageCMDBUtil
from plugins.DistributedStorage.utils.common.DeployConstant import DeployConstant, DeployType


class UpdateCMDB(TestCase, DistributedStorageRegCMDBBase):
    def __init__(self, project_id, pod_id, regionid_list, fs_args,
                 condition=None, metadata=None, **kwargs):
        super(UpdateCMDB, self).__init__(project_id, pod_id)
        self.condition = condition
        self.metadata = metadata
        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)
        self.vm_opr = VMOperate(self.project_id, self.pod_id, None)

    def procedure(self):
        logger.info('Start update CMDB.')
        try:
            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.")
        except HCCIException as e:
            logger.error('update CMDB failed:{}'.format(e))
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error('update CMDB failed:{}'.format(e))
            logger.error(traceback.format_exc())
            raise HCCIException(620008, str(e))
        return Message(200)

    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)
        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["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["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_vm_hostname_list = self.fs_cmdb_util.get_fsm_hostname_list(name)
        logger.info("fsm_vm_hostname_list:{}".format(fsm_vm_hostname_list))
        return fsm_vm_hostname_list
