# -*- coding:utf-8 -*-
import os
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
import utils.common.log as logger
from utils.common.exception import FCUException
from utils.business.dmk_util import DmkApi
from utils.common.software_package_util import find_software_package_by_name
from utils.business.param_util import ParamUtil
from plugins.eBackup.common.util import Utils


class UploadPackageToDmk(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list):
        super(UploadPackageToDmk, self).__init__(self, project_id, pod_id)
        logger.init("eBackup")
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.__dmk_util = DmkApi()
        self.util = ParamUtil()
        self.__db_param_dict = Utils.init_system_params(project_id,
                                                        regionid_list[0])

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            self._upload_package_to_dmk()
            return Message(200)
        except FCUException as e:
            return Message(500, e)
        except Exception as e:
            logger.error("Failed to upload package to DMK for eBackup"
                         " plugin,the reason is %s" % e)
            return Message(500, FCUException(650008, 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)

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

    def _upload_package_to_dmk(self):

        # upload the package eBackup DMK.
        update_scene = self.__db_param_dict["update_scene"]
        logger.info("eBackup: upload eBckup-DMK package start in [%s scene]" %
                    update_scene)

        package_post_name = 'eBackup_Upgrade_DMK.zip' if \
            update_scene == 'upgrade' else 'eBackup_Patch_DMK.zip'

        path, name = find_software_package_by_name(
            pkg_pre_name="OceanStor",
            pkg_post_name=package_post_name,
            project_id=self.project_id)
        if name == "":
            raise FCUException(650018, "OceanStor BCManager %s_%s" %
                               (self.__db_param_dict["eBackup_Version"],
                                package_post_name))
        file_path = os.path.join(path, name)

        self.__dmk_util.login_dmk(self.__db_param_dict['dmk_floatIp'],
                                  self.__db_param_dict['eBackup_dmk_user'],
                                  self.__db_param_dict['eBackup_dmk_password'])
        result = self.__dmk_util.upload_pkg_to_dmk(
            self.__db_param_dict['dmk_floatIp'],
            self.__db_param_dict['dmk_os_business_username'],
            self.__db_param_dict['dmk_os_business_user_password'],
            file_path, self.pod_id)
        if result:
            logger.info("eBackup: upload eBackup-DMK package success.")
        else:
            logger.error("eBackup: upload eBackup-DMK package failed")
            raise FCUException(
                650013,
                "OceanStor BCManager %s_%s" %
                (self.__db_param_dict["eBackup_Version"], package_post_name),
                self.__db_param_dict['dmk_floatIp'])
