
#include <stdio.h>
#include <stdlib.h>

#include "../mecha/mecha.h"

#include "file_entry.h"
#include "file_catalog.h"

struct s_FileCatalog
{
    hshTvoid_list *file_by_id;
    hshTvoid_list *file_by_filename;
};

FileCatalog *
file_catalog_new (void)
{
    FileCatalog *instance = (FileCatalog *) malloc (sizeof (FileCatalog));

    instance->file_by_id = hshFvoid_int_init (file_entry_destroy);
    instance->file_by_filename = hshFvoid_init (NULL);

    return (instance);
}

void
file_catalog_destroy (void *ptr)
{
    FileCatalog *instance = (FileCatalog *) ptr;

    hshFvoid_destroy (instance->file_by_id);
    hshFvoid_destroy (instance->file_by_filename);

    free (instance);
}

int
file_catalog_get_fileid (FileCatalog *instance, const char *filename)
{
    FileEntry *entry;
    
    entry = (FileEntry *) hshFvoid_find (instance->file_by_filename, filename);

    if (entry == NULL)
    {
        entry = file_entry_new (filename);

        hshFvoid_add (instance->file_by_filename, filename, entry);
        hshFvoid_int_add (instance->file_by_id, file_entry_get_fileno (entry), entry);
    }

    return (file_entry_get_fileno (entry));
}

FileEntry *
file_catalog_get_file_entry (FileCatalog *instance, int fileId)
{
    FileEntry *entry;

    entry = (FileEntry *) hshFvoid_int_find (instance->file_by_id, fileId);

    return (entry);
}
