/* map temporary file */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

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

#include "elinks.h"

#include "document/libdom/mapa.h"
#include "util/string.h"

void
save_in_map(void *m, void *node, int length)
{
	ELOG
	struct el_mapa *mapa = (struct el_mapa *)m;

	if (!mapa) {
		return;
	}

	if (mapa->size == mapa->allocated) {
		struct el_node_elem *tmp = mem_realloc(mapa->table, mapa->size * 2 * sizeof(*tmp));

		if (!tmp) {
			return;
		}
		mapa->table = tmp;
		mapa->allocated = mapa->size * 2;
	}

	mapa->table[mapa->size].offset = length;
	mapa->table[mapa->size].node = node;
	mapa->size++;
}

void
save_offset_in_map(void *m, void *node, int offset)
{
	ELOG
	save_in_map(m, node, offset);
}

void *
create_new_element_map(void)
{
	ELOG
	struct el_mapa *mapa = (struct el_mapa *)mem_calloc(1, sizeof(*mapa));

	if (!mapa) {
		return NULL;
	}
	struct el_node_elem *tmp = mem_calloc(256, sizeof(*tmp));

	if (!tmp) {
		mem_free(mapa);
		return NULL;
	}
	mapa->table = tmp;
	mapa->size = 0;
	mapa->allocated = 256;

	return mapa;
}

void *
create_new_element_map_rev(void)
{
	ELOG
	return create_new_element_map();
}

void
delete_map(void *m)
{
	ELOG
	struct el_mapa *mapa = (struct el_mapa *)m;

	if (mapa) {
		mem_free(mapa->table);
		mem_free(mapa);
	}
}

static int
compare(const void *a, const void *b)
{
	ELOG
	int offa = ((struct el_node_elem *)a)->offset;
	int offb = ((struct el_node_elem *)b)->offset;

	return offa - offb;
}

void *
find_in_map(void *m, int offset)
{
	ELOG
	struct el_mapa *mapa = (struct el_mapa *)m;

	if (!mapa) {
		return NULL;
	}
	struct el_node_elem key = { .offset = offset, .node = NULL };
	struct el_node_elem *item = (struct el_node_elem *)bsearch(&key, mapa->table, mapa->size, sizeof(*item), compare);

	if (!item) {
		return NULL;
	}
	return item->node;
}

static int
compare_nodes(const void *a, const void *b)
{
	ELOG
	void *nodea = ((struct el_node_elem *)a)->node;
	void *nodeb = ((struct el_node_elem *)b)->node;

	if (nodea < nodeb) {
		return -1;
	}

	if (nodea > nodeb) {
		return 1;
	}

	return 0;
}

int
find_offset(void *m, void *node)
{
	ELOG
	struct el_mapa *mapa = (struct el_mapa *)m;

	if (!mapa) {
		return -1;
	}
	struct el_node_elem key = { .offset = -1, .node = node };
	struct el_node_elem *item = (struct el_node_elem *)bsearch(&key, mapa->table, mapa->size, sizeof(*item), compare_nodes);

	if (!item) {
		return -1;
	}
	return item->offset;
}

void
sort_nodes(void *m)
{
	ELOG
	struct el_mapa *mapa = (struct el_mapa *)m;

	if (!mapa) {
		return;
	}
	qsort(mapa->table, mapa->size, sizeof(struct el_node_elem), compare_nodes);
}
