# -*- coding: utf-8 -*-
import os
import utils.common.log as logger
from utils.common.exception import FCDException as FCUException
from plugins.DistributedStorage.scripts.logic.UpgradeOperate import UpgradeOperate
from utils.common.fic_base import TestCase
import traceback


class DistributePkg(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None,
                 metadata=None, **kwargs):
        super(DistributePkg, self).__init__(project_id, pod_id)
        self.condition = condition
        self.metadata = metadata
        self.more_args = kwargs
        self.opr = UpgradeOperate(fs_args)
        self.user_name = fs_args.get("user_name", "admin")
        self.password = fs_args["dm_update_pwd"]
        self.float_ip = fs_args["float_ip"]
        self.port = fs_args.get("port", "8088")
        self.package_file = fs_args["package_path"]
        self.package_name = fs_args["package_name"]

    def procedure(self):
        try:
            self.log_dm()

            self.check_version()

            logger.info('validaty package %s.' % self.package_name)
            package_size = os.path.getsize(self.package_file)
            ret_result, ret_data = self.opr.package_validaty(
                self.package_name, package_size)
            if ret_result["code"] != '0':
                err_msg = "Validaty %s failed, Detail:[result:%s, data:%s]" \
                          % (self.package_name, ret_result, ret_data)
                logger.error(err_msg)
                raise Exception(err_msg)

            logger.info('set version upgrade mode.')
            version_upgrade_mode = 2
            ret_result, ret_data = self.opr.set_upg_mode(version_upgrade_mode)
            if ret_result["code"] != '0':
                err_msg = "set upgrade to version mode failed, " \
                          "Detail:[result:%s, data:%s]" \
                          % (ret_result, ret_data)
                logger.error(err_msg)
                raise Exception(err_msg)

            logger.info('upload package %s to node.' % self.package_file)
            ret_result, ret_data = self.opr.upload_upg_pkg(self.package_file)
            if ret_result["code"] != '0':
                err_msg = "upload package failed, Detail:[result:%s, data:%s]"\
                          % (ret_result, ret_data)
                logger.error(err_msg)
                raise Exception(err_msg)

        except FCUException as e:
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error(traceback.format_exc())
            raise FCUException(626314, str(e))
        finally:
            logger.info('procedure end.')

    def log_dm(self):
        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)

    def check_version(self):
        """
        检查当前存储版本判断是否需要升级
        :return:
        """
        rsp_result, rsp_data = self.opr.get_product()
        if rsp_result.get("code") != 0:
            err_msg = "Failed to get product, Detail:[result:%s]%s" % (
                rsp_result, rsp_data)
            logger.error(err_msg)
            raise FCUException(626313, err_msg)
        version = rsp_data.get("version")
        if version != "8.0.1.SPC600":
            logger.error("version is %s, skip!" % rsp_data)
            return
        if not self.package_file or not self.package_name:
            err_msg = "The package is not exist"
            logger.error(err_msg)
            raise FCUException(626313, err_msg)
