# -*- 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


class SaveSandBoxStatusInf(StepBaseInterface, ABC):
    def __init__(self, project_id, pod_id, regionid_list=None, suit_id=None):
        super(SaveSandBoxStatusInf, 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()

    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及之后版本，一跳升级，需保存安全沙箱
        sandbox_opr = SandBoxHandlerForUpgrade(self.fs_args)
        if not sandbox_opr.is_after_813:
            logger.info("Current Version:{}, no sandbox, pass".format(sandbox_opr.version))
            return
        logger.info("sandbox initial status:{}".format(sandbox_opr.sandbox_initial_status))
        self.params_util.set_service_cloud_param(
            self.project_id,
            SERVICE_NAME,
            self.region_id,
            "FSM_{}_active_sandbox_status".format(self.suit_id),
            str(sandbox_opr.sandbox_initial_status.get(self.fs_args.get("master_ip")))
        )
        self.params_util.set_service_cloud_param(
            self.project_id,
            SERVICE_NAME,
            self.region_id,
            "FSM_{}_standby_sandbox_status".format(self.suit_id),
            str(sandbox_opr.sandbox_initial_status.get(self.fs_args.get("slaver_ip")))
        )
        logger.info("Sandbox status saved successfully.")
