# coding=utf-8
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback

import utils.common.log as logger
from utils.common.message import Message
from utils.common.fic_base import TestCase
from utils.common.exception import HCCIException
from utils.common.fic_base import StepBaseInterface
from utils.DBAdapter.DBConnector import BaseOps
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.logic.deploy_operate import FusionStorageOperate


class CheckPassword(TestCase):
    def __init__(self, project_id, pod_id):
        self.pod_id = pod_id
        self.project_id = project_id
        self.db = BaseOps()
        logger.error("project_id :%s pod_id：%s" % (project_id, pod_id))

    @staticmethod
    def check_rest_password(address, login_user, login_passwd):
        operate = FusionStorageOperate(float_ip=address)
        status_code, error_code, error_des = operate.login(login_user, login_passwd)
        if status_code != 200 or error_code != 0:
            err_msg = "Failed to login rest, Detail:[status:%s,code:%s]%s" % (
                status_code, error_code, error_des)
            logger.error(err_msg)
            raise Exception(err_msg)

    def procedure(self):
        """
        检查输入的密码是否正确，包括FSM admin的密码，所有节点的密码。
        扩AZ复用 TenantStorFBReuse80&(ExpansionAZ_KVM)
        扩计算节点 (TenantStorFBReuse80|TenantStorFB80)&(ExpansionComputeRes_KVMNode|ExpansionNetworkRes_NetworkNode)
        """
        if get_project_condition_boolean(self.project_id, 'TenantStorFBReuse80&ExpansionAZ_KVM'):
            logger.info("The type of project is : TenantStorFBReuse80&ExpansionAZ_KVM")
            # 检查业务存储的 Portal的admin用户的密码
            expansion_az_fsm_float_ip = \
                self.db.get_user_input_cloud_param_by_key(self.project_id, "expansion_az_fsm_float_ip")
            reuse_fsm_admin_passwd = self.db.get_user_input_cloud_param_by_key(
                self.project_id, "reuse_fsm_admin_passwd")
            if len(reuse_fsm_admin_passwd) != 0:
                self.check_rest_password(expansion_az_fsm_float_ip, "admin", reuse_fsm_admin_passwd)

        if get_project_condition_boolean(
                self.project_id,
                '(TenantStorFB80|TenantStorFBHCI80)&(ExpansionComputeRes_KVMNode|ExpansionNetworkRes_NetworkNode)'):
            # 检查业务存储的 Portal的admin用户的密码
            reuse_fsm_admin_passwd = self.db.get_user_input_cloud_param_by_key(
                self.project_id, "reuse_fsm_admin_passwd")
            reuse_fsm_float_ip = self.db.get_user_input_cloud_param_by_key(
                self.project_id, "reuse_fsm_float_ip")
            self.check_rest_password(reuse_fsm_float_ip, "admin", reuse_fsm_admin_passwd)

        logger.info('Passed the check')


class CheckPasswordInterface(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(CheckPasswordInterface, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.implement = CheckPassword(project_id, pod_id)

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：执行安装前的资源预检查，该接口由execute接口调用，工具框架不会直接调用此接口。
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def execute(self, project_id, pod_id):
        try:
            self.implement.procedure()
        except HCCIException as e1:
            logger.error('pwd check error:{}'.format(traceback.format_exc()))
            return Message(500, e1)
        except Exception as e2:
            logger.error('pwd check error:{}'.format(traceback.format_exc()))
            return Message(500, e2)
        return Message(200)

    def rollback(self, project_id, pod_id):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def retry(self, project_id, pod_id):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(project_id, pod_id)

    def check(self, project_id, pod_id):
        """
        标准调用接口：重试
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)
