# -*- coding: utf-8 -*-
import secrets
import utils.common.log as logger
from utils.common import message
from utils.common.exception import HCCIException
from utils.common.fic_base import TestCase
from plugins.DistributedStorage.Replication.scripts.common_utils.config_params import Params
from utils.common.fic_base import ToolClient
from plugins.DistributedStorage.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorage.Replication.scripts.common_utils.RestOperate import RestOperate
from plugins.DistributedStorage.logic.InstallOperate import InstallOperate
from utils.business.project_condition_utils import get_project_condition_boolean


class Domain(TestCase):

    def __init__(self, project_id, pod_id):
        super(Domain, self).__init__(project_id, pod_id, step_id=None, metadata=None)
        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')

    def pre_condition(self):
        pass

    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')
            # 本端地址池ip列表, 默认全部复制节点都加入地址池
            local_ip_pool_ip_list = param_lld["ip_pool"]

            if self.config_license_switch_condition:
                self.install_operate.config_create_pool_license_switch(self.pod_id, float_ip)
            self.pod_id = self.args_dict['pod_id']
            self.project_id = self.args_dict['project_id']

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

            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)
            return message.Message(200)
        except HCCIException as e:
            return message.Message(500, str(e))
        except Exception as e:
            return message.Message(500, HCCIException(627117, str(e)))
        finally:
            if self.config_license_switch_condition:
                self.install_operate.config_create_pool_license_switch(self.pod_id, float_ip, delete=True)

    def create_hyper_metro_domain(self, control_cluster_id, domain_name, domain_type, device_id, cmd_pwd):
        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 HCCIException(627117, msg)
