# -*- coding: utf-8 -*-
import utils.common.log as logger
from utils.common.exception import HCCIException
from plugins.DistributedStorage.common.UpgradeOperate import UpgradeOperate
from plugins.DistributedStorage.common.base import TestCase
import traceback
from utils.business.project_util import ProjectApi


class SaveVersion(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None,
                 metadata=None, **kwargs):
        super(SaveVersion, self).__init__(project_id, pod_id)
        self.condition = condition
        self.metadata = metadata
        self.more_args = kwargs
        self.opr = UpgradeOperate(fs_args)
        self.float_ip = fs_args["float_ip"]
        self.port = fs_args["port"]
        self.user_name = fs_args["user_name"]
        self.password = fs_args["password"]

    def procedure(self):
        try:
            status_code, error_code, error_des = self.opr.try_login(
                self.user_name, self.password)
            if status_code != 200 or error_code != 0:
                err_msg = "Failed to login, Detail:[status:%s,code:%s]%s" % (status_code, error_code, error_des)
                logger.error(err_msg)
                raise Exception(err_msg)

            logger.info('get cluster product version.')
            ret_result, ret_data = self.opr.get_product()
            if ret_result["code"] != 0:
                err_msg = "get cluster product failed, Detail: [result:%s, data:%s]" % (ret_result, ret_data)
                logger.error(err_msg)
                raise Exception(err_msg)
            product_version = ret_data["version"]
            product_model = ret_data["product_model"]
            component_name = product_model + "_" + self.float_ip

            logger.info('get upgrade packages.')
            ret_result, ret_data = self.opr.get_upgrade_packages()
            if ret_result["code"] != '0':
                err_msg = "get upgrade packages failed, " \
                          "Detail:[result:%s, data:%s]" \
                          % (ret_result, ret_data)
                logger.error(err_msg)
                raise Exception(err_msg)
            packages_version = ret_data["version"]

            logger.info("save origin version:{0}, target version:{1}".format(
                product_version, packages_version))
            info_version = {"Originalversion": product_version,
                            "Targetversion": packages_version}
            # 保存当前版本和目标版本的信息
            ProjectApi().save_version_info(self.project_id, component_name,
                                           info_version)
        except HCCIException as e:
            logger.error('save version failed,details:{}'.format(e))
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error('save version failed,details:{}'.format(e))
            logger.error(traceback.format_exc())
            raise HCCIException(620006, str(e))
