# -*- coding: utf-8 -*-
"""
Storage 升级任务
"""
import os
import utils.common.log as logger
from utils.common.exception import HCCIException
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
from plugins.DistributedStorage.Upgrade.scripts.impl.TC_Upgrade_Hotpatch import HotpatchUpgradePkg
from plugins.DistributedStorage.common.ParameterGain import ParamsGain
from plugins.DistributedStorage.common.UpgradeHotPatchOperate import UpgradeHotPatchOperate
from plugins.DistributedStorage.common.constants import UpgradeStateKey


class HotpatchUpgrade(StepBaseInterface):
    """
    Packege Upgrade class
    """
    def __init__(self, project_id, pod_id, regionid_list, suit_id=None):
        super(HotpatchUpgrade, self).__init__(project_id, pod_id, regionid_list)
        self.fs_args = ParamsGain(project_id, pod_id,
                                  regionid_list).get_args(suit_id)
        self.fs_args["upgrade_type"] = "upgrade"
        pkg_name, pkg_dir = ParamsGain(project_id, pod_id,
                                       regionid_list).get_storage_hot_package()
        self.fs_args["package_name"] = pkg_name
        self.fs_args["package_path"] = os.path.join(pkg_dir, pkg_name)
        self.upgrade_state_key = UpgradeStateKey.HOTPATCH_UPGRADE_STATE.format(suit_id)
        self.fs_args["hotpatch_upgrade_key"] = self.upgrade_state_key

    def execute(self, project_id, pod_id, regionid_list=None, suit_id=None):
        """
        Perform an upgrade task
        """
        logger.info('Start packege upgrade task.')
        try:
            UpgradeHotPatchOperate.init_operate_state(project_id, regionid_list[0], self.upgrade_state_key)
            HotpatchUpgradePkg(project_id, pod_id, self.fs_args).run()
        except HCCIException as e:
            logger.error('Upgrade pkg failed.')
            return Message(500, e)
        except Exception as e:
            logger.error('Upgrade pkg failed.')
            return Message(500, HCCIException(620009, str(e)))
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None, suit_id=None):
        """
        标准调用接口：重试
        :return: Message对象
        """
        logger.info('Start packege upgrade retry task.')
        try:
            HotpatchUpgradePkg(project_id, pod_id, self.fs_args).retry()
        except HCCIException as e:
            logger.error('Failed to upload the package again.')
            return Message(500, e)
        except Exception as e:
            logger.error('Failed to upload the package again.')
            return Message(500, HCCIException(620009, str(e)))
        return Message(200)
