# -*- coding:utf-8 -*-
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
import utils.common.log as logger
from plugins.eBackup.common.eBackupUpgrade import EbackupUpgrader
from plugins.eBackup.common.util import Utils


class WorkflowRollback(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None):
        super(WorkflowRollback, self).__init__(project_id, pod_id,
                                               regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.__db_param_dict = Utils.init_system_params(project_id,
                                                        regionid_list[0])

    def pre_check(self, project_id, pod_id, regionid_list=None):
        pass

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            host_info = self.__db_param_dict['eBackup_Workflow_nodes']
            host_info = host_info.replace(" ", "").split("|")

            all_result = []
            logger.info("Begin to rollback all workflow nodes(%s)" %
                        str(host_info))
            for host_ips in host_info:
                host_ips = host_ips.split(";")
                logger.info("Begin to rollback workflow nodes(%s)" %
                            str(host_ips))
                ebckup_upgrade = EbackupUpgrader(host_ips,
                                                 self.__db_param_dict,
                                                 "workflow")
                is_true = ebckup_upgrade.rollback()
                if not is_true:
                    logger.error("Fail to rollback workflow nodes(%s)" %
                                 str(host_ips))
                else:
                    logger.info("Rollback workflow nodes(%s) successfully." %
                                str(host_ips))
                all_result.append(is_true)

            if False in all_result:
                logger.error("Fail to rollback all workflow nodes.")
                return Message(500, error_msg_cn="回退Workflow失败，"
                                                 "请登录DMK查看失败原因，"
                                                 "请勿直接重试",
                               error_msg_en="Rollback Workflow failed, please "
                                            "log in DMK to see the "
                                            "details, do not directly retry")

            logger.info("Rollback all datamover nodes successfully.")
            return Message(200)

        except Exception as e:
            logger.error("Failed to rollback workflow ,the reason is %s" % e)
            return Message(500, str(e), str(e))

    def rollback(self, project_id, pod_id, regionid_list=None):
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None):
        return self.execute(project_id, pod_id, regionid_list)
