# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback
from abc import ABC

import utils.common.log as logger
from utils.common.message import Message
from utils.common.fic_base import StepBaseInterface
from utils.business.param_util import ParamUtil
from plugins.DistributedStorage.common.parameter_gain import ParamsGain
from plugins.DistributedStorage.common.constants import SERVICE_NAME
from plugins.DistributedStorage.logic.sandbox_operate import SandBoxHandlerForUpgrade, ENABLE_STATUS


class RecoverySandBoxStatusInf(StepBaseInterface, ABC):
    def __init__(self, project_id, pod_id, regionid_list=None, suit_id=None):
        super(RecoverySandBoxStatusInf, self).__init__(project_id, pod_id, regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.region_id = regionid_list[0]
        self.suit_id = suit_id
        self.fs_args = ParamsGain(project_id, pod_id, regionid_list).get_args(suit_id)
        self.params_util = ParamUtil()
        self.sandbox_opr = SandBoxHandlerForUpgrade(self.fs_args)

    def execute(self, project_id, pod_id, regionid_list=None, suit_id=None):
        try:
            self.procedure()
        except Exception as err:
            logger.error("Sandbox error:{}, details:{}".format(err, traceback.format_exc()))
            return Message(500, err)
        return Message()

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

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

    def procedure(self):
        # 813及之后版本，一跳升级，需恢复安全沙箱；
        if not self.sandbox_opr.is_after_813:
            logger.info("Current Version:{}, no sandbox, pass".format(self.sandbox_opr.version))
            return

        logger.info("Start to restore the sandbox status.")

        fsm_active_sandbox_status = self.params_util.get_value_from_cloud_param(
            self.project_id,
            SERVICE_NAME,
            "FSM_{}_active_sandbox_status".format(self.suit_id),
            self.region_id
        )
        self.recover_sandbox_status(self.fs_args.get("master_ip"), fsm_active_sandbox_status)
        logger.info("The node {} is restored successfully.".format(self.fs_args.get("master_ip")))

        fsm_standby_sandbox_status = self.params_util.get_value_from_cloud_param(
            self.project_id,
            SERVICE_NAME,
            "FSM_{}_standby_sandbox_status".format(self.suit_id),
            self.region_id
        )
        self.recover_sandbox_status(self.fs_args.get("slaver_ip"), fsm_standby_sandbox_status)
        logger.info("The node {} is restored successfully.".format(self.fs_args.get("slaver_ip")))

    def recover_sandbox_status(self, ip_addr, status: str):
        if int(status) == ENABLE_STATUS:
            self.sandbox_opr.do_enable_fsm_sandbox([ip_addr])
        else:
            self.sandbox_opr.do_disable_fsm_sandbox(self.sandbox_opr.request_body.get(ip_addr))
