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

import utils.common.log as logger
from utils.common.exception import FCDException
from utils.common.fic_base import TestCase
from utils.common.fic_base import ToolClient
from platforms.project.ProjectUtils import get_project_condition_boolean
from plugins.DistributedStorage.scripts.logic.InstallOperate import InstallOperate
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorageReplication.scripts.common_utils.rest_operate import RestOperate
from plugins.DistributedStorageReplication.scripts.common_utils.config_params import Params


class Domain(TestCase):

    def __init__(self, project_id, pod_id):
        super(Domain, self).__init__(project_id, pod_id, step_id=None, metadata=None)
        self.project_id = self.args_dict['project_id']
        self.pod_id = self.args_dict['pod_id']
        self.service_name = 'FusionStorageBlockReplication'
        self.client = None
        self.default_client = ToolClient.DSWARE_CLIENT
        self.install_operate = InstallOperate(project_id, pod_id)
        self.config_license_switch_condition = get_project_condition_boolean(self.project_id, '!TenantStorFBReuse80')
        self.opr = None

    def procedure(self):
        try:
            log_module_name = self.args_dict['log_module_name']
            logger.init(log_module_name)

            # 本端FSM参数信息
            logger.info("[FSBR]Start to Create HyperMetroDomain.")
            param_lld = Params(self.project_id, self.pod_id, self.service_name).get_params_dict()
            float_ip = param_lld["local_storage_fsm_ip"]
            cmd_pwd = param_lld.get('local_admin_password')
            root_pwd = param_lld.get('local_storage_fsm_root_password')
            # 本端地址池ip列表, 默认全部复制节点都加入地址池
            local_ip_pool_ip_list = param_lld["ip_pool"]

            logger.info("[FSBR] Start to login fsm. ")
            self.opr = RestOperate(float_ip)
            self.opr.login(DeployConstant.DM_LOGIN_USER, cmd_pwd)

            if self.config_license_switch_condition:
                # 扩云服务场景 关闭本端FSM节点沙箱
                if get_project_condition_boolean(self.project_id, 'ExpansionAdCloudService'):
                    self.install_operate.disable_fsm_sandbox(self.opr, root_pwd, cmd_pwd)
                self.install_operate.config_create_pool_license_switch(self.pod_id, float_ip)

            logger.info("[FSBR] Start to query control cluster id.")
            result = self.opr.query_control_cluster()
            control_cluster_id = result.get_control_cluster_id()
            if not control_cluster_id:
                msg = "[FSBR] Create hyper domain fail, not found control cluster id. detail: \n %s" % result.res.json()
                logger.error(msg)
                raise Exception(msg)

            # 双活域名称 随机生成  如，domain_01
            string = "domain_"
            domain_name = string + str(secrets.SystemRandom().choice(list(range(0, 100))))

            # 双活域类型
            def_type = "HC_DOMAIN_TYPE_AA"
            domain_type = def_type  # default HC_DOMAIN_TYPE_AA

            # 远端设备ID
            result = self.opr.query_remote_device(control_cluster_id)
            device_id = result.get_remote_device_id(local_ip_pool_ip_list)
            if not device_id:
                msg = "[FSBR] Create hyper domain fail, not found remote device id. detail: \n %s" % result.res.json()
                logger.error(msg)
                raise Exception(msg)

            # 创建双活域
            logger.info("Start to create hyper metro domain.")
            self.create_hyper_metro_domain(*[control_cluster_id, domain_name, domain_type, device_id, cmd_pwd])
        finally:
            if self.config_license_switch_condition:
                if get_project_condition_boolean(self.project_id, 'ExpansionAdCloudService'):
                    # 扩云服务场景 开启本端FSM节点沙箱
                    self.install_operate.enable_fsm_sandbox(self.opr)
                self.install_operate.config_create_pool_license_switch(self.pod_id, float_ip, delete=True)

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(20), reraise=True)
    def create_hyper_metro_domain(self, *args):
        control_cluster_id, domain_name, domain_type, device_id, cmd_pwd = args
        result = self.opr.create_hyper_domain(control_cluster_id, domain_name, domain_type, device_id)
        ret_value = result.query_dr_cmd_result()
        if 0 == ret_value:
            logger.info("[FSBR] Create hyper metro domain success.")
            self.opr.login_out(DeployConstant.DM_LOGIN_USER, cmd_pwd)
        else:
            msg = '[FSBR]Create hyper metro domain failed. detail:\n%s' % result.res.json()
            logger.error(msg)
            raise FCDException(627117, msg)
