#ifndef YTMDL_APP_H
#define YTMDL_APP_H

#include <pthread.h>

#include "queue.h"

#define CONCURRENT_DOWNLOADS 2
#define OUTPUT_DIR_CAP 1024
#define AUDIO_FORMAT_CAP 16
#define MESSAGE_CAP 256

typedef struct {
    Queue queue;

    pthread_mutex_t settings_lock;
    char output_dir[OUTPUT_DIR_CAP];
    int playlist_folders;
    char audio_format[AUDIO_FORMAT_CAP];

    int work_ids[MAX_QUEUE_ITEMS];
    int work_head, work_tail, work_count;
    pthread_mutex_t work_lock;
    pthread_cond_t work_cond;
    int shutdown;
    pthread_t workers[CONCURRENT_DOWNLOADS];

    pthread_mutex_t message_lock;
    char message[MESSAGE_CAP];
    int message_ttl_ticks;
    int message_is_error;
} App;

void app_init(App *app, const char *output_dir, const char *audio_format);
void app_start_workers(App *app);
void app_shutdown(App *app);

/* Spawns a detached thread to resolve+enqueue the given URL. */
void app_submit_url(App *app, const char *url);

void app_set_output_dir(App *app, const char *path);
void app_get_output_dir(App *app, char *out, size_t cap);

void app_set_playlist_folders(App *app, int enabled);
int app_get_playlist_folders(App *app);

void app_clear_finished(App *app);
void app_remove_item(App *app, int id);
void app_retry_item(App *app, int id);

void app_notify(App *app, int is_error, const char *fmt, ...);
/* Copies the current message into out (empty string if none/expired) and
 * ticks its remaining lifetime down by one. */
void app_get_message(App *app, char *out, size_t cap, int *is_error);

#endif
