/* all-projs.m,
 *
 * A registry for projectiles.  Also handles (un)loading of data.
 *
 * Projectiles that need to load data need to add (inside initialize):
 *	REGISTER_PROJECTILE(self);
 *
 * Units using the projectile need to add (inside loadPrerequisites):
 *	LOAD_PROJECTILE_DATA_FOR(projectile);
 */

#include <assert.h>
#include "common.h"
#include "debug.inc"
#include "projectiles/all-projs.h"
#include "thing.h"


#define MAX_PROJECTILE_CLASSES		10


static struct {
    BOOL loaded, required;
    Class class;
} proj_data[MAX_PROJECTILE_CLASSES];


static unsigned int total_proj_classes;

/*------------------------------------------------------------*/

static int find_class_index(Class class)
{
    unsigned int i;

    for (i = 0; i < total_proj_classes; i++)
	if (proj_data[i].class == class)
	    return i;
    return -1;
}

BOOL load_projectile_data_for(Class class)
{
    int i = find_class_index(class);

    if (i < 0)	      /* This projectile doesn't need to load data. */
	return YES;

    proj_data[i].required = YES;
    if (not proj_data[i].loaded) {
	if (not (proj_data[i].loaded = [proj_data[i].class loadData]))
	    fprintf(stderr, "Error loading %s datafiles.\n", [proj_data[i].class name]);
    }

    return proj_data[i].loaded;
}

void unload_unnecessary_projectile_data(void)
{
    unsigned int i;

    for (i = 0; i < total_proj_classes; i++) {
	if (proj_data[i].loaded && not proj_data[i].required) {
#ifdef DEBUG_LOG_SHUTDOWN_PROJECTILES
	    printf("Shutting down %s.\n", [proj_data[i].class name]);
#endif
	    [proj_data[i].class shutdown];
	    proj_data[i].loaded = NO;
	}
    }
}

void mark_all_projectile_data_unnecessary(void)
{
    unsigned int i;

    for (i = 0; i < total_proj_classes; i++)
	proj_data[i].required = NO;
}

/*------------------------------------------------------------*/

void register_projectile(Class class)
{
#ifdef DEBUG_LOG_REGISTER_PROJECTILES
    printf("Registering %s\n", [class name]);
#endif

    assert(total_proj_classes+1 < MAX_PROJECTILE_CLASSES);
    proj_data[total_proj_classes].class = class;
    proj_data[total_proj_classes].loaded = NO;
    proj_data[total_proj_classes].required = NO;

    total_proj_classes++;
}
