# -*- coding: utf-8 -*-
import os
import time
import utils.common.log as logger
from utils.common.exception import HCCIException
from plugins.DistributedStorage.common.base import TestCase
from utils.client.FSPAuthClient import FSPAuthClient
from utils.DBAdapter.DBConnector import BaseOps
from utils.common.software_package_util import find_software_package
import traceback


class UpdateUVPPkg(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None,
                 metadata=None, **kwargs):
        super(UpdateUVPPkg, self).__init__(project_id, pod_id)
        self.condition = condition
        self.metadata = metadata
        self.more_args = kwargs
        self.pkg_regular = fs_args["pkg_regular"]
        self.upload_uvp_flag = fs_args.get("upload_uvp")

    def procedure(self):
        logger.info('Start update UVP package task.')
        try:
            if not self.upload_uvp_flag:
                logger.info("Not need upload UVP package, return!")
                return
            pkg_dict, num = find_software_package(self.pkg_regular,
                                                  self.project_id)
            if num > 1:
                logger.error("The package is not unique. %s" % str(pkg_dict))
                raise HCCIException(620020)
            if pkg_dict:
                cps_client = FSPAuthClient.get_cps_rest_client(
                    BaseOps(), self.project_id, self.pod_id)
                logger.info("get client: %s" % cps_client)
                while self._delete_uvp_manager_pkg(cps_client):
                    logger.info("delete fusion storage manager pkg.")
                pkg_name = list(pkg_dict.keys())[0]
                pkg_dir = list(pkg_dict.values())[0]
                pkg_path = os.path.join(pkg_dir, pkg_name)
                self._upload_uvp_pkg(cps_client, pkg_name, pkg_path)
            else:
                logger.warn("The UVP package is not exist")

        except HCCIException as e:
            logger.error('upload UVP package failed:{}'.format(e))
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error('upload UVP package failed:{}'.format(e))
            logger.error(traceback.format_exc())
            raise HCCIException(620008, str(e))
        finally:
            logger.info('procedure end.')

    @staticmethod
    def _delete_uvp_manager_pkg(cps_client):
        pkg_info_list = cps_client.do_package_instance_list()
        logger.info(pkg_info_list)
        for pkg_info in pkg_info_list:
            pkg_service_name = pkg_info.get("pkg_service_name")
            if pkg_service_name == "FusionStorage_Manager":
                pkg_version = pkg_info.get("version")
                if pkg_version != "FusionStorage_Manager_8.x":
                    raise Exception("version is not 8.x")
        return False

    @staticmethod
    def _upload_uvp_pkg(cps_client, pkg_name, pkg_path):
        logger.info("upload %s" % pkg_name)
        pkg_uuid = cps_client.do_package_upload(pkg_name, pkg_path)
        logger.info(pkg_uuid)
        check_out = 1800
        while check_out > 0:
            res = cps_client.do_package_upload_status(pkg_uuid)
            logger.info("uploading %s" % res)
            if res.get("status") == "uploaded":
                break
            time.sleep(10)
            check_out -= 10
        if check_out <= 0:
            raise Exception("timeout")
