# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback
from tenacity import retry, stop_after_attempt, wait_fixed

import utils.common.log as logger
from utils.common.fic_base import TestCase
from utils.client.FSPAuthClient import FSPAuthClient


class ConfigKVMResourcePoolFather(TestCase):
    def __init__(self, project_id, pod_id):
        super(ConfigKVMResourcePoolFather, self).__init__(project_id, pod_id)

    @classmethod
    def query_template_name_by_float_ip(cls, float_ip: str, cluster_data: dict):
        cluster_list = cluster_data.get('cluster_list')
        for cluster_info in cluster_list:
            params = cluster_info.get("params")
            host = params.get("host")
            cinder_drivers = params.get("cinder_drivers")
            for cinder_driver in cinder_drivers:
                cfg = cinder_driver.get("cfg")
                dsware_manager = cfg.get("dsware_manager")
                logger.info("host:{}, dsware_manager:{}, float_ip:{}".format(host, dsware_manager, float_ip))
                if dsware_manager == float_ip:
                    template_name = "cinder-volume-" + host.split("-")[1]
                    logger.info("Template name:{}".format(template_name))
                    return template_name
        raise Exception("The Cinder-kvm with the floating IP address[{}] does not exist".format(float_ip))

    def get_old_fscli_cfg(self, float_ip: str, resource_pool_data: dict, service_name="cinder"):
        template_name = self.query_template_name_by_float_ip(float_ip, resource_pool_data)

        cps_rest_client = FSPAuthClient.get_cps_rest_client(self.db, self.project_id, self.pod_id)
        template_cfg = cps_rest_client.do_template_params_show(service_name, template_name)
        other_storage_cfg = template_cfg.get("other_storage_cfg")

        for _, value in other_storage_cfg.items():
            default = value.get("DEFAULT")
            dsware_manager = default.get("dsware_manager")
            if dsware_manager == float_ip:
                logger.info("Get fscli_cfg success.")
                return default
        err_msg = "Failed to query the DistributedStorage[{0}] other_storage_cfg parameter in {1}, " \
                  "cmd: cps template-params-show --service cinder {1}".format(float_ip, template_name)
        logger.error(err_msg)
        raise Exception(err_msg)

    @retry(stop=stop_after_attempt(2), wait=wait_fixed(2), reraise=True)
    def update_fscli_cfg(self, float_ip: str, cinder_kvm: str, old_fscli_cfg: dict, service_name="cinder"):
        template_name = "cinder-volume-" + cinder_kvm.split("-")[1]

        def _cps_template_params_update():
            cps_rest_client.do_template_params_update(service_name, template_name, params)
            cps_rest_client.do_commit()

        cps_rest_client = FSPAuthClient.get_cps_rest_client(self.db, self.project_id, self.pod_id)
        template_cfg = cps_rest_client.do_template_params_show(service_name, template_name)
        other_storage_cfg = template_cfg.get("other_storage_cfg")
        for _, value in other_storage_cfg.items():
            new_fscli_cfg = value.get("DEFAULT")
            dsware_manager = new_fscli_cfg.get("dsware_manager")
            if dsware_manager != float_ip:
                continue
            new_fscli_cfg["fsc_cli_connect_key_pw"] = old_fscli_cfg.get("fsc_cli_connect_key_pw")
            new_fscli_cfg["fsc_cli_connect_ca"] = old_fscli_cfg.get("fsc_cli_connect_ca")
            new_fscli_cfg["fsc_cli_connect_cert"] = old_fscli_cfg.get("fsc_cli_connect_cert")
            new_fscli_cfg["fsc_cli_connect_key"] = old_fscli_cfg.get("fsc_cli_connect_key")

        params = {"other_storage_cfg": template_cfg.get("other_storage_cfg")}
        try:
            _cps_template_params_update()
        except Exception as err:
            logger.error("Fail to update service name: {}, template name: {}, "
                         "details:{}".format(service_name, template_name, traceback.format_exc()))
            cps_rest_client.do_rollback()
            raise err
        logger.info("template name:{}, fscli cfg updated successfully.".format(template_name))
