#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import re
import utils.common.log as logger
from utils.common.fic_base import TestCase
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorageReplication.scripts.common_utils.config_params import Params
from plugins.DistributedStorageReplication.scripts.common_utils.rest_operate import RestOperate


class CreateRemoteDeviceO1(TestCase):

    def __init__(self, project_id, pod_id):
        super(CreateRemoteDeviceO1, self).__init__(project_id, pod_id)
        self.project_id = self.args_dict['project_id']
        self.pod_id = self.args_dict['pod_id']
        self.service_name = "FusionStorageBlockReplication"
        self.opr = None
        self.remote_opr = None
        all_params = Params(self.project_id, self.pod_id, self.service_name).get_params_dict()
        self.float_ip = all_params.get('local_storage_fsm_ip')
        self.cmd_passwd = all_params.get('local_admin_password')
        self.remote_ip_pool_id = '1'
        self.psk_label = all_params.get('PSK_Label')
        self.psk_passwd = all_params.get('PSK_password')
        self.remote_float_ip = all_params.get("remote_storage_fsm_ip")
        self.remote_cmd_pwd = all_params.get("produce_admin_password")
        self.cluster_info = all_params.get("replication_cluster_nodes_info")
        self.ip_pool_ip_list = [info.get('replication_network') for info in self.cluster_info]

    def procedure(self):
        log_module_name = self.args_dict['log_module_name']
        logger.init(log_module_name)
        logger.info("[FSBR] Start to create remote device.")

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

        logger.info("[FSBR] Start to query control cluster id.")
        control_cluster_id = self.query_control_cluster_id()

        logger.info("[FSBR] Start to query local ippool id, local ippool ip")
        local_ip_pool_id, initial_local_ip = self.query_local_ippool(self.ip_pool_ip_list, control_cluster_id)

        logger.info("[FSBR] Start to query remote ippool ip.")
        logger.info("[FSBR] Start to login remote fsm %s." % self.remote_float_ip)
        self.remote_opr = RestOperate(self.remote_float_ip)
        self.remote_opr.login(DeployConstant.DM_LOGIN_USER, self.remote_cmd_pwd)

        initial_remote_ip = self.query_remote_ippool(control_cluster_id, self.remote_ip_pool_id)

        logger.info("Start to create remote device.")
        remote_device_params = {'ctl_cluster_id': control_cluster_id,
                                'local_ip_pool_id': local_ip_pool_id,
                                'remote_ip_pool_id': self.remote_ip_pool_id,
                                'initial_local_ip': initial_local_ip,
                                'initial_remote_ip': initial_remote_ip,
                                'psk_label': self.psk_label,
                                'psk_passwd': self.psk_passwd}
        result = self.opr.create_remote_device(remote_device_params)
        ret_value = result.query_dr_cmd_result()
        if 0 == ret_value:
            logger.info("[FSBR] Create remote device success.")
            self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.cmd_passwd)
        else:
            err_msg = "Create remote device fail. detail: \n%s" % result.res.json()
            logger.error(err_msg)
            raise Exception(err_msg)

    def query_control_cluster_id(self):
        result = self.opr.query_control_cluster()
        control_cluster_id = result.get_control_cluster_id()
        if not control_cluster_id:
            msg = "[FSBR] Create remote device fail, not found control cluster id. detail: \n %s" \
                  % result.res.json()
            logger.error(msg)
            raise Exception(msg)
        return control_cluster_id

    def query_local_ippool(self, ip_pool_ip_list, control_cluster_id):
        initial_local_ip = ip_pool_ip_list[0].split(',')[0]
        result = self.opr.query_ip_pool_info(control_cluster_id)
        local_ip_pool_id = result.get_ip_pool_id(initial_local_ip)
        if not local_ip_pool_id:
            msg = "[FSBR] Create remote device fail, not found local IP pool id. detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)
        logger.info("[FSBR] End to query params. detail: \n"
                    "controlClusterId: %s, localIpPoolId: %s, initialLocalIp: %s" %
                    (control_cluster_id, local_ip_pool_id, initial_local_ip))
        return local_ip_pool_id, initial_local_ip

    def query_remote_ippool(self, control_cluster_id, remote_ip_pool_id):
        result = self.remote_opr.query_ip_pool_info(control_cluster_id)
        initial_remote_ip = result.get_remote_init_ip(remote_ip_pool_id)
        if not initial_remote_ip:
            msg = "[FSBR] Create remote device fail, can not get remote init IP. detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)
        logger.info("[FSBR] Query remote ippool ip success, remote IP: %s" % initial_remote_ip)
        return initial_remote_ip

    def parse_resp(self, resp):
        """创建远端设备回显特殊，需要对内容解析判断创建与否"""
        temp_str = "".join(resp).strip()
        pattern = re.compile("-{3,}(.*?)-{3,}", re.DOTALL)
        res = pattern.findall(temp_str)
        if res:
            code = res[0].strip().split()[-1]
            if code == "0":
                return True
            else:
                return False
        logger.error("[FSBR] Parse fail with create remote device result.result:%s" % temp_str)
        raise Exception("[FSBR] Parse fail with create remote device result.result:%s" % temp_str)

    def post_condition(self):
        pass

    def failure(self):
        pass
