#!/usr/bin/env python
# -*- coding: utf-8 -*-

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 CreateReplicateCluster_01(TestCase):
    def __init__(self, project_id, pod_id):
        super(CreateReplicateCluster_01, 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']
        logger.info("[FSBR] Start to create replicate cluster.")
        try:

            logger.info("[FSBR] Start to get LLD params.")
            # 统一的获取参数信息

            all_params = Params(self.project_id, self.pod_id, self.service_name).get_params_dict()
            cluster_info = all_params.get("replication_cluster_nodes_info")
            service_ip_list = [info.get('replication_manage_ip') for info in cluster_info]
            float_ip = all_params.get('local_storage_fsm_ip')
            cmd_passwd = all_params.get('local_admin_password')

            logger.info("[FSBR] End to get LLD params.")

            self.opr = RestOperate(float_ip)
            status_code, error_code, error_des = self.opr.login(DeployConstant.DM_LOGIN_USER, cmd_passwd)
            if status_code != 200 or error_code != 0:
                err_msg = "Failed to login fusionstorage manager, Detail:[status:%s,code:%s]%s" \
                          % (status_code, error_code, error_des)
                logger.error(err_msg)
                raise Exception(err_msg)

            logger.info("[FSBR] Start to check vbs, replication server and driver")
            ip_str = ",".join(service_ip_list)
            self.evn_pre_check(ip_str)
            logger.info("[FSBR] Check vbs replication server, driver success")

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

            logger.info("[FSBR] End to read params. control_id:%s,ip_list: %s" % (control_cluster_id, service_ip_list))
            logger.info("[FSBR] Start to create replicate cluster.")
            result = self.opr.create_replication_cluster(service_ip_list, control_cluster_id)
            ret_value = result.query_dr_cmd_result()
            if 0 == ret_value:
                logger.info("[FSBR] Create replicate cluster success.")
                self.opr.login_out(DeployConstant.DM_LOGIN_USER, cmd_passwd)
                return message.Message(200)
            else:
                msg = "[FSBR] Create replicate cluster fail. detail: \n %s" % result.res.json()
                logger.error(msg)
                raise Exception(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(627137, str(e)))

    def evn_pre_check(self, ip_str):
        res = self.opr.query_dsware_client()
        dsware_client_list = res.get_dsware_client_list()
        ip_list = ip_str.split(",")
        box = []
        for ip_addr in ip_list:
            if ip_addr not in dsware_client_list:
                box.append(ip_addr)
        if box:
            err_msg = "[FSBR] Check vbs result:fail.detail: %s" % dsware_client_list
            logger.error(err_msg)
            raise Exception(err_msg)

    def post_condition(self):
        pass

    def failure(self):
        pass
