#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from plugins.DistributedStorage.Replication.scripts.common_utils.config_params import Params
from utils.common.fic_base import TestCase
import utils.common.log as logger
from utils.common import message
from utils.common.exception import HCCIException
from plugins.DistributedStorage.utils.common.DeployConstant import DeployConstant
from plugins.DistributedStorage.Replication.scripts.common_utils.RestOperate import RestOperate


class CreateRemoteDevice_o1(TestCase):

    def __init__(self, project_id, pod_id):
        super(CreateRemoteDevice_o1, self).__init__(project_id, pod_id)
        self.service_name = "FusionStorageBlockReplication"

    def pre_condition(self):
        pass

    def procedure(self):
        log_module_name = self.args_dict['log_module_name']
        logger.init(log_module_name)
        self.pod_id = self.args_dict['pod_id']
        self.project_id = self.args_dict['project_id']
        try:
            logger.info("[FSBR] Start to create remote device.")
            logger.info("[FSBR] Start to get LLD params.")

            all_params = Params(self.project_id, self.pod_id, self.service_name).get_params_dict()

            float_ip = all_params.get('local_storage_fsm_ip')
            cmd_passwd = all_params.get('local_admin_password')
            remoteIpPoolId = '1'
            PSK_label = all_params.get('PSK_Label')
            PSK_passwd = all_params.get('PSK_password')
            remote_float_ip = all_params.get("remote_storage_fsm_ip")
            remote_cmd_pwd = all_params.get("produce_admin_password")
            cluster_info = all_params.get("replication_cluster_nodes_info")
            ip_pool_ip_list = [info.get('replication_network') for info in cluster_info]
            logger.info("[FSBR] End to get LLD params.")

            logger.info("[FSBR] Start to login fsm. ")
            self.opr = RestOperate(float_ip)
            self.opr.login(DeployConstant.DM_LOGIN_USER, 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(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." % remote_float_ip)
            self.remote_opr = RestOperate(remote_float_ip)
            self.remote_opr.login(DeployConstant.DM_LOGIN_USER, remote_cmd_pwd)

            initial_remote_ip = self.query_remote_ippool(control_cluster_id, remoteIpPoolId)

            logger.info("Start to create remote device.")
            result = self.opr.create_remote_device(control_cluster_id, local_ip_pool_id, remoteIpPoolId,
                                                   initial_local_ip, initial_remote_ip, PSK_label, PSK_passwd)
            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, cmd_passwd)
                return message.Message(200)
            else:
                err_msg = "Create remote device fail. detail: \n%s" % result.res.json()
                logger.error(err_msg)
                raise Exception(err_msg)
        except HCCIException as e:
            logger.error(e)
            return message.Message(500, str(e))
        except Exception as e:
            logger.error(e)
            return message.Message(500, HCCIException(627140, str(e)))

    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
