#!/usr/bin/env python3

import os
from custom_operators.qarnot_utils import qarnot_general


def fetch_output(
        task_uuid,
        job_uuid,
        path_outputs,
        path_config_qarnot,
        download_locally,
        snapshot_wait_sec,
        path_local_logging_config,
        delete_task):
    """This function:
    - updates the output bucket
    - synchronizes your local directory with the output bucket
    - manages the logs
    """

    try:
        # Configure the logger
        logger = qarnot_general.configure_logger(path_local_logging_config)
        logger.debug("Logger configured successfully")

        # Connection to Qarnot task
        conn = qarnot_general.qarnot_connection(path_config_qarnot, logger)
        task = conn.retrieve_task(task_uuid)
        job = conn.retrieve_job(job_uuid)

        if task.state == 'FullyExecuting':
            # sync ouptput files of the qarnot machine with the bucket
            task.instant()
            # necessary to wait for a few seconds
            logger.debug("Wait {} seconds before downloading"
                         .format(snapshot_wait_sec))
            task.wait(snapshot_wait_sec)
            # sync the bucket with your local directory if option selected
            if download_locally:
                logger.debug("Starts downloading results")
                task.download_results(path_outputs)
        else:
            logger.warn("Task state was not 'FullyExecuting', "
                        + "no download launched")

        logger.debug("Local output folder now contains the following files:")
        for x in os.listdir(path_outputs):
            logger.debug(x)

        # Display errors on failure and raise airflow exception
        qarnot_general.check_failure(task, job, delete_task, logger)

        # raise an airflow exception if the task was cancelled
        qarnot_general.check_cancellation(task, job, delete_task, logger)

    except Exception:
        qarnot_general.handle_error(logger, delete_task, task, job)
