# -*- coding:utf-8 -*-
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
import utils.common.log as logger
from utils.DBAdapter.DBConnector import BaseOps
from utils.common.exception import FCUException
from plugins.eBackup.common.eBackupDriverUpgrade import EbackupDriverUpgrader
from utils.common.ssh_util import Ssh
from plugins.eBackup.common.util import Utils


class DriverRollback(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list):
        super(DriverRollback, 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.database = BaseOps()
        self.__db_param_dict = Utils.init_system_params(project_id,
                                                        regionid_list[0])
        self.__ssh = Ssh()

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

    def _execute_rollback(self, reverse_proxy_ip):
        try:
            driver_upgrade = EbackupDriverUpgrader(reverse_proxy_ip,
                                                   self.__db_param_dict)
            rollback_result = driver_upgrade.rollback()
            return rollback_result
        except Exception as ex:
            logger.error("Exception occurs:" + str(ex))
            return False

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            region_type = self.database.get_region_type(self.project_id)
            logger.info("The network type is %s" % region_type)
            reverse_proxy_ip = \
                self.__db_param_dict['openstack_reverse_proxy_ip']
            is_true = self._execute_rollback(reverse_proxy_ip)
            if not is_true:
                logger.info("Fail to Upgrade eBackup driver.")
                return Message(500, "Fail to Upgrade eBackup driver.")
            return Message(200)
        except FCUException as ex:
            logger.error("Exception occurs when rollback "
                         "eBackup driver: " + str(ex))
            return Message(500, ex)
        except Exception as e:
            logger.error("Rollback eBackup driver failed, "
                         "the reason is: " + str(e))
            return Message(500, error_msg_cn="回退eBackup Driver失败，"
                                             "请查看日志详情",
                           error_msg_en="Rollback eBackup Driver failed, "
                                        "please see the log for detail")

    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)
