# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import utils.common.log as logger
from utils.common.fic_base import TestCase
from utils.client.FSPAuthClient import FSPAuthClient
from utils.Driver.CloudDC.OpenStack.config_cascading_kvm import ConfinCascadingKvm
from plugins.DistributedStorage.logic.deploy_operate import DeployOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant
from plugins.DistributedStorage.logic.install_operate import InstallOperate


class ConfigKVMResourcePool(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(ConfigKVMResourcePool, self).__init__(project_id, pod_id)
        self.fs_args = fs_args
        self.float_ip = self.fs_args.get('float_ip')
        self.vbs_list = self.fs_args.get('vbs_list')
        self.backend_name = self.fs_args.get('backend_name')
        self.opr = DeployOperate(self.fs_args)
        self.more_args = kwargs
        self.install_opr = InstallOperate(self.project_id, self.pod_id, fs_args)

    def procedure(self):
        logger.info("Start to config cinder connect fusionstoarge.")
        cps_client = FSPAuthClient.get_cps_web_client(self.db, self.project_id, self.pod_id)
        private_key_psw = self.install_opr.upload_cert_and_get_private_key(cps_client)

        compute_ip_list = [vbs['om_ip'] for vbs in self.vbs_list]
        compute_id_list = [vbs['hostname'] for vbs in self.vbs_list]
        webui_client = FSPAuthClient.get_cps_web_client(self.db, self.project_id, self.pod_id)

        self.opr.login(DeployConstant.DM_LOGIN_USER, self.fs_args['dm_update_pwd'])
        logger.info("Query storage pool data.")
        res_pool = self.opr.query_storage_pool()
        pool_info = res_pool.get_query_data()
        if len(pool_info.get('storagePools')) == 0:
            logger.error('check pool fail...')
            raise Exception("check pool fail...")
        pool_id_list = [str(pool.get('poolId')) for pool in pool_info.get('storagePools')]
        pool_id_list = ','.join(pool_id_list)
        self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.fs_args['dm_update_pwd'])

        over_ratio = self.db.get_value_from_cloudparam(self.pod_id, "DistributedStorageBusiness",
                                                       "business_thin_alloc_rate")
        logger.info("Config cinder connect fusionstoarge.")

        az = self.db.get_user_input_cloud_param_by_key(self.project_id, "openstack_region")
        obj = ConfinCascadingKvm(webui_client)
        cluster_name = obj.get_storage_resource_cluster_name_kvm_fusionstorage(az, self.backend_name)
        if cluster_name:
            self.logger_info("The resource:%s is exist; To avoid duplication of configuration, "
                             "need to delete first" % cluster_name)
            obj.delete_resource(cluster_name)
        # 增加FusionStorage的融合部署的动作
        max_vbs_num = 3
        if len(compute_ip_list) > max_vbs_num:
            compute_ip_list = compute_ip_list[:max_vbs_num]
        fusionstorageagent = ",".join(compute_ip_list)

        max_host_num = 3
        if len(compute_id_list) > max_host_num:
            compute_id_list = compute_id_list[:max_host_num]
        obj.config_cascaded_kvm(self.backend_name, self.float_ip, fusionstorageagent, pool_id_list, over_ratio,
                                compute_id_list, az, private_key_psw)
        self.logger_info("config cinder connect fusionstoarge success.")

    def failure(self):
        super(ConfigKVMResourcePool, self).failure()
        # 环境恢复脚本
