#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.

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 CreateRepClsPSKOne(TestCase):
    def __init__(self, project_id, pod_id):
        super(CreateRepClsPSKOne, 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

    def procedure(self):

        log_module_name = self.args_dict['log_module_name']
        logger.init(log_module_name)

        logger.info("[FSBR] Start config PSK_label and PSK_passwd.")
        # 获取LLD中的配置的预共享标签及密钥信息

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

        logger.info("[FSBR] Start to get LLD params.")
        psk_label, psk_passwd = all_params.get("PSK_Label"), all_params.get('PSK_password')
        # dswaretool 工具cmdadmin 用户密码 后续鉴权用
        float_ip = all_params.get('local_storage_fsm_ip')
        cmd_passwd = all_params.get('local_admin_password')

        logger.info("[FSBR] End t 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 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] Config PSK_label and PSK_passwd fail, not found control cluster id. " \
                  "detail: \n %s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)

        logger.info("[FSBR] Start to create RepClsPSK.")
        result = self.opr.create_rep_cls_psk(control_cluster_id, psk_label, psk_passwd)
        ret_value = result.query_dr_cmd_result()
        if 0 != ret_value:
            msg = "Config PSK_label and PSK_passwd fail. detail: \n%s" % result.res.json()
            logger.error(msg)
            raise Exception(msg)

        logger.info("Config PSK_label adn PSK_passwd success.")
        self.opr.login_out(DeployConstant.DM_LOGIN_USER, cmd_passwd)
