# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import time
from utils.common.fic_base import TestCase
import utils.common.log as logger
from utils.common.exception import HCCIException
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.logic.deploy_operate import DeployOperate
from plugins.DistributedStorage.logic.install_operate import InstallOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant


class EnableEncryption(TestCase):
    def __init__(self, project_id, pod_id, fs_args):
        super(EnableEncryption, self).__init__(project_id, pod_id)
        self.fs_args = fs_args
        self.opr = DeployOperate(fs_args)
        self.install_operate = InstallOperate(project_id, pod_id, fs_args)
        self.float_ip = fs_args.get('float_ip')
        self.update_pwd = fs_args.get('dm_update_pwd')
        self.encrypted_condition = get_project_condition_boolean(self.project_id, 'FsEncrypted')
        self.internal_kms_condition = get_project_condition_boolean(self.project_id, 'FsBuiltInEncrypted')
        self.external_kms_condition = get_project_condition_boolean(self.project_id, 'FsExternalEncrypted')

    def procedure(self):
        logger.info("Start to turn on encryption switch.")
        # 关闭license限制
        logger.info("Star to turn off encryption license restrictions.")
        self.config_encryption_license_switch(check_encrption=False)
        logger.info("Finish turn off encryption license restrictions.")
        # 登录deploy manager
        logger.info("Start to login deploy manager.")
        self.login_deploy_manager()
        # 开启加密开关
        logger.info("Turn on the encryption switch.")
        self.open_encryption()
        # 恢复license限制
        logger.info("Star to turn on encryption license restrictions.")
        self.config_encryption_license_switch(check_encrption=True)
        logger.info("Finish turn on encryption license restrictions.")
        logger.info("Turn on encryption switch successful.")
        self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.update_pwd)

    def config_encryption_license_switch(self, check_encrption):
        if self.encrypted_condition:
            logger.info("Start to config license check encryption switch")
            self.install_operate.config_encryption_license_switch(self.pod_id, self.float_ip, check_encrption)
            logger.info("Finish to config license check encryption switch")
            logger.info("Restart oam-s")
            self.install_operate.restart_oams(self.pod_id, self.float_ip)
            logger.info('Restart oam-s end.')
            time.sleep(10)

    def login_deploy_manager(self):
        status_code, error_code, error_des = self.opr.login(DeployConstant.DM_LOGIN_USER,
                                                            self.update_pwd, keep_session=True)
        if status_code != 200 or error_code != 0:
            err_msg = "Failed to login deploy manager, " \
                      "Detail:[status:%s,code:%s]%s" % (status_code, error_code, error_des)
            logger.error(err_msg)
            raise Exception(err_msg)

    def open_encryption(self):
        # 开启加密场景，判断内置/外置，kms_type取值 0：内置密管 1：外置密管
        kms_type = 0
        if self.internal_kms_condition:
            kms_type = 0
        elif self.external_kms_condition:
            kms_type = 1
        rsp = self.opr.create_encrypted_account(DeployConstant.DM_LOGIN_USER, self.update_pwd, kms_type)
        if rsp.get('status_code') != 0 or rsp.get('error_code') is not None:
            err_msg = "Failed to enable encryption. Detail:[status:%s " \
                      "code:%s]%s" % (rsp.get('status_code'), rsp.get('error_code'), rsp.get('error_msg'))
            logger.error(err_msg)
            raise HCCIException(626363, err_msg)
        if rsp.get('data').get('kmsType') != kms_type:
            err_msg = "Failed to enable encryption. Actual kms type [%s] is not " \
                      "expected kms type [%s]" % (rsp.get('data').get('kmsType'), kms_type)
            logger.error(err_msg)
            raise HCCIException(626363, err_msg)
        logger.info("Enable encryption successful.")
