# -*- 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.fic_base import TestCase
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.Replication.scripts.common_utils.config_params import Params
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant
from plugins.DistributedStorage.Replication.scripts.common_utils.rest_operate import RestOperate
from plugins.DistributedStorage.logic.install_operate import InstallOperate


class CreateQuorumServerOne(TestCase):
    def __init__(self, project_id, pod_id):
        super(CreateQuorumServerOne, self).__init__(project_id, pod_id, step_id=None, metadata=None)
        self.service_name = "FusionStorageBlockReplication"
        self.install_operate = InstallOperate(project_id, pod_id)
        self.config_license_switch_condition = get_project_condition_boolean(
            self.project_id, '!(ExpansionAdCloudService|ExpansionServiceStorage&CSHAStorage_TFB&!TenantStorFB80)')
        parameters = Params(self.project_id, self.pod_id, self.service_name)
        lld_dict = parameters.get_params_dict()
        self.address_ip_list = lld_dict.get("ip_pool")
        self.fsa_ip_list = lld_dict.get("replication_cluster")
        self.control_ip_list = lld_dict.get("replication_controller_cluster")

        self.remote_fsm_float_ip = lld_dict.get("remote_storage_fsm_ip")
        self.remote_fsadmin_password = lld_dict.get("remote_storage_fsm_fsadmin_password")
        self.remote_admin_password = lld_dict.get("produce_admin_password")
        self.remote_root_password = lld_dict.get("remote_storage_fsm_root_password")

        self.local_fsm_float_ip = lld_dict.get("local_storage_fsm_ip")
        self.local_admin_password = lld_dict.get('local_admin_password')
        self.local_fsadmin_passwd = lld_dict.get("local_storage_fsm_fsadmin_password")
        self.local_root_passwd = lld_dict.get("local_storage_fsm_root_password")

        self.quorumserverip = lld_dict.get("storage_arbitration_ip")

        # 远端控制集群id
        self.remote_cluster_id = None
        self.local_cluster_id = None
        self.remote_opr = RestOperate(self.remote_fsm_float_ip)
        self.opr = RestOperate(self.local_fsm_float_ip)

    @staticmethod
    def generate_random_str(randomlength=24):
        """仲裁服务器的名字"""
        random_str = ''
        base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
        length = len(base_str) - 1
        for _ in range(randomlength):
            random_str += base_str[secrets.choice(list(range(0, length)))]
        return random_str

    @staticmethod
    def query_control_cluster_id(opr: RestOperate):
        result = opr.query_control_cluster()
        control_cluster_id = result.get_control_cluster_id()
        if not control_cluster_id:
            msg = "[FSBR]Not found Replication control cluster id. " \
                  "float_IP: {}, detail:{}".format(opr.float_ip, result.res.json())
            logger.error(msg)
            raise Exception(msg)
        logger.info("[FSBR] query control cluster id success ")
        return control_cluster_id

    def procedure(self):
        # 1 预准备：登录本端、远端存储，检查复制控制集群ID
        logger.info("[FSBR] Start to login fsm. ")
        self.opr.login(DeployConstant.DM_LOGIN_USER, self.local_admin_password)
        logger.info("[FSBR] Start to login remote fsm. ")
        self.remote_opr.login(DeployConstant.DM_LOGIN_USER, self.remote_admin_password)
        self.local_cluster_id = self.query_control_cluster_id(self.opr)
        self.remote_cluster_id = self.query_control_cluster_id(self.remote_opr)
        quorum_server_ip_port = self.quorumserverip + ":30002"

        # 2 创建本端仲裁服务器： 关license限制 - 创建仲裁服务器
        logger.info("[FSBR]Creating a Local Quorum Server, float ip:{}".format(self.local_fsm_float_ip))
        if self.config_license_switch_condition:
            self.install_operate.config_license_switch(
                self.local_fsm_float_ip, DeployConstant.FSM_USER, self.local_fsadmin_passwd, self.local_root_passwd)
        try:
            self.create_local_quorum_server(quorum_server_ip_port)
        finally:
            if self.config_license_switch_condition:
                self.install_operate.config_license_switch(
                    self.local_fsm_float_ip, DeployConstant.FSM_USER,
                    self.local_fsadmin_passwd, self.local_root_passwd, delete=True)
            self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.local_admin_password)
        logger.info("[FSBR]Create local QuorumServer successfully, float ip:{}".format(self.local_fsm_float_ip))

        # 3 创建远端仲裁服务器： 关沙箱 - 关license限制 - 创建仲裁服务器
        logger.info("[FSBR]Creating a remote Quorum Server, float ip:{}".format(self.remote_fsm_float_ip))
        if self.config_license_switch_condition:
            # 关闭远端FSM节点沙箱
            self.install_operate.disable_fsm_sandbox(
                self.remote_opr, self.remote_root_password, self.remote_admin_password)
            self.install_operate.config_license_switch(self.remote_fsm_float_ip, DeployConstant.FSM_USER,
                                                       self.remote_fsadmin_password, self.remote_root_password)
        try:
            self.create_remote_quorum_server(quorum_server_ip_port)
        finally:
            if self.config_license_switch_condition:
                self.install_operate.config_license_switch(
                    self.remote_fsm_float_ip, DeployConstant.FSM_USER,
                    self.remote_fsadmin_password, self.remote_root_password, delete=True)
                self.install_operate.enable_fsm_sandbox(self.remote_opr)
            self.remote_opr.login_out(DeployConstant.DM_LOGIN_USER, self.remote_admin_password)
        logger.info("[FSBR]Create remote QuorumServer successfully, float ip:{}".format(self.local_fsm_float_ip))

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(20), reraise=True)
    def create_local_quorum_server(self, quorum_server_ip_port):
        local_quorm_name = self.generate_random_str()
        result = self.opr.create_quorum_server(local_quorm_name, quorum_server_ip_port, self.local_cluster_id)
        ret_value = result.query_dr_cmd_result()
        if 0 != ret_value:
            msg = "[FSBR] Failed to create local quorum server. detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)
        logger.info("[FSBR]local  createQuorumServer success ")

    @retry(stop=stop_after_attempt(3), wait=wait_fixed(20), reraise=True)
    def create_remote_quorum_server(self, quorum_server_ip_port):
        remote_quorm_name = self.generate_random_str()
        result = self.remote_opr.create_quorum_server(remote_quorm_name, quorum_server_ip_port,
                                                      self.remote_cluster_id)
        ret_value = result.query_dr_cmd_result()
        if 0 != ret_value:
            msg = "[FSBR] Failed to create remote quorum server. detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)
