#include <stdlib.h>
#include <db.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <sys/types.h>

#include "avltree.h"

#define	PAGESIZE	512
#define	KEYSIZE		16
#define	VALSIZE		sizeof(void *)
#define	ENTSIZE		(KEYSIZE+VALSIZE)


static DB			*dbP;

void
avl_create_index(AVL_IX_DESC *pix, int dup, int flag)
{
	static	BTREEINFO	bt1 = {
		0,			/* flags */
		65536,		/* cachesize */
		0,			/* maxkeypage */
		PAGESIZE/ENTSIZE,	/* minkeypage */
		PAGESIZE,		/* psize */
		NULL,			/* compare */
		NULL,			/* prefix */
		0,			/* lorder */
	};

	bt1.flags = dup ? R_DUP : 0;
	dbP = dbopen(NULL, O_CREAT|O_RDWR, 0644, DB_BTREE, &bt1);
	if (dbP == NULL) {
		perror("dbopen");
		exit(1);
	}
}


int
avl_add_key(AVL_IX_REC *pe, AVL_IX_DESC *pix)
{
	int	ret;
	DBT	key;
	DBT	data;

	memset(&key, 0, sizeof(key));
	memset(&data, 0, sizeof(data));

	key.data = pe->key;
	key.size = strlen(pe->key);

	data.data = &pe->recptr;
	data.size = sizeof(pe->recptr);

	ret = dbP->put(dbP, &key, &data, 0);
	if (ret == -1) {
		perror("get");
		exit(1);
	} else if (ret == 1)
		return AVL_IX_FAIL;

	return AVL_IX_OK;
}

int
avl_find_key(AVL_IX_REC *pe, AVL_IX_DESC *pix)
{
	int	ret;
	DBT	key;
	DBT	data;

	key.data = pe->key;
	key.size = strlen(pe->key);

	ret = dbP->get(dbP, &key, &data, 0);
	if (ret == -1) {
		perror("get");
		exit(1);
	} else if (ret == 1)
		return AVL_IX_FAIL;

	if (data.size != sizeof(pe->recptr)) {
		fprintf(stderr, "find_key: bad recptr size %d\n", data.size);
		exit(1);
	}
	return AVL_IX_OK;
}
