#!/usr/bin/env python3

import os
from custom_operators.qarnot_utils import qarnot_general


def stop_cluster(task_uuid,
                 job_uuid,
                 path_config_qarnot,
                 path_local_logging_config,
                 path_config_cluster,
                 delete_task):
    """This function:
    - aborts the task
    - manages the logs
    - deletes the task and job if delete_task is True
    - removes the config cluster file

    Args:
    - task_uuid (str): uuid of the Qarnot task
    - job_uuid (str): uuid of the Qarnot job
    - path_config_qarnot (str) (ex: os.path.join(path_airflow, \
    'config/qarnot.conf')): Configuration file to connect to Qarnot API
    - path_local_logging_config (str) (ex: os.path.join(path_airflow,\
    'config/python_local_logging.conf')): Path to python logging config file \
    in the local machine
    - delete_task (bool optional): if set to True, deletes task and job once \
    the cluster is closed, by default set to False
    - path_config_cluster (str) (ex: os.path.join(path_airflow,\
    'config/tmp_config/cluster.conf')): Path to the config folder of the \
    cluster
    """

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

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

        # 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)

        # Finally closes the cluster
        logger.debug("End of task, closing the cluster")
        task.abort()

        # Remove config cluster directory
        logger.debug("Remove config file")
        os.remove(path_config_cluster)

        if delete_task:
            qarnot_general.del_task_job(task, job, logger)

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