/*
 * bg.c
 *
 * Wrapper over pthread with the addition of some interthread comms.
 *
 * HEADER FILE
 *
 * History:
 *      20250904 Creation from imgmover prototype.
 *
 * Author: Dario Rodriguez dario@darionomono.com
 * (c) Dario Rodriguez 2025
 * This program is licensed under the terms of GNU GPL v2.1+
 */

#ifndef BG_H
#define BG_H

#include <time.h>
#include <sys/time.h>
#include "raylib.h"

typedef struct bgload_t {
        /* main/thread ownership management */
        int lended_to_thread; // written from main, read from thread
        int thread_finished; // written from thread, read from main
        int is_todo;  // written from main, read from thread
        int has_mark;  // written/read from main
        /* data only accessed from owner */
        char path[1024]; // to use only from owner
        Image image; // to use only from owner
        int has_data; // to use only from owner
        int has_failedload; // to use only from owner
        time_t lastused; // to don't purge until some time has passed after load
        struct timeval tv_lastadded; // to be able to load the "most recently added bgload" first
} bgload_t;

typedef struct bg_t {
        int sizebgload;
        bgload_t *bgload;
        pthread_t thread;
        char pinnedpath[1024];
        pthread_attr_t tattr;
        int flag_threadstarted;
        int do_exit;
} bg_t;


void bg_staticinit(void);
void bg_staticfini(void);

bg_t *bg_init(int sizebgload);
void bg_free(bg_t *bg);
int bg_resetmarks(bg_t *bg);
bgload_t *bg_get(bg_t *bg, char *path);
int bg_add(bg_t *bg, char *path, int flag_pinned); /* only one image is pinned (excluded from unload) */
int bg_freeunmarked(bg_t *bg);

void *bg_thread(void *);


#endif