# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import os
import traceback
import utils.common.log as logger
from utils.common.exception import HCCIException
from plugins.DistributedStorage.common.base import TestCase
from plugins.DistributedStorage.common.upgrade_operate import UpgradeOperate


class DistributePkg(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(DistributePkg, self).__init__(project_id, pod_id)
        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"]
        self.package_file = fs_args["package_path"]
        self.package_name = fs_args["package_name"]

    def procedure(self):
        try:
            self.main()
        except HCCIException as e:
            logger.error('Distributed pkg check failed,details:{}'.format(e))
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error('Distributed pkg check failed,details:{}'.format(e))
            logger.error(traceback.format_exc())
            raise HCCIException(620006, str(e)) from e

    def main(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)

        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)
