#include "engine/declarations.h"

#include "declarations_app.h"
#include "catalog.h"



int catalog_read(char *s) {
	return(catalog_create_op(s, FILE_MODE_READ));
}

int catalog_create(char *s) {
	return(catalog_create_op(s, FILE_MODE_WRITE_AND_TRUNCATE));
}

static int catalog_create_op(char *s, char *m) {
	if(p_file != 0) {
		(void) set_error(EIO);

		LOGWARN(ERROR_SLIGHT, SUBSYSTEM,
			_("Failed to open catalog '%s' in mode %s, catalog '%s' is already opened"),
				s, m, files_get_name(p_file));

		return(-1);
	}

	if((p_file = files_open(s, 0, m)) == 0) {
		return(-1);
	}

	p_offs = -1;

	return(0);
}

int catalog_close(void) {
	if(catalog_check() != 0) {
		return(-1);
	}

	if(files_close(p_file) != 0) {
		return(-1);
	}

	p_file = 0;

	return(0);
}

int catalog_entry_open(void) {
	long p;

	uint64_t s;

	if(catalog_check() != 0) {
		return(-1);
	}

	if(p_offs != -1) {
		/* Store current file position as pointer to next entry in previous entry */
		if((p = files_tell(p_file)) == -1) {
			return(-1);
		}

		if(files_seek(p_file, p_offs, FILE_SEEK_SET) != 0) {
			return(-1);
		}

		s = (uint64_t) p;

		if(files_write(p_file, &s, sizeof(s)) != 0) {
			return(-1);
		}

		if(files_seek(p_file, p, FILE_SEEK_SET) != 0) {
			return(-1);
		}
	}

	/* Store empty pointer for next entry */
	if((p_offs = files_tell(p_file)) == -1) {
		return(-1);
	}

	s = 0;

	return(files_write(p_file, &s, sizeof(s)));
}

int catalog_entry_item_save(void *s, size_t t) {
	if(catalog_check() != 0) {
		return(-1);
	}

	return(files_write(p_file, s, t));
}

int catalog_header(void) {
	struct cat_header c;

	if(catalog_check() != 0) {
		return(-1);
	}

	c.id = CATALOG_ID;

	c.version = CATALOG_VERSION_CURRENT;
#if defined(IS_BIGENDIAN)
	c.endian = CATALOG_ENDIAN_BIG;
#else
	c.endian = CATALOG_ENDIAN_LITTLE;
#endif
	c.size = (uint32_t) sizeof(struct cat_header);

	c.t_char = (uint32_t) sizeof(char);
	c.t_int = (uint32_t) sizeof(int);
	c.t_long = (uint32_t) sizeof(long);
	c.t_float = (uint32_t) sizeof(float);
	c.t_double = (uint32_t) sizeof(double);
	c.t_int8_t = (uint32_t) sizeof(int8_t);
	c.t_int16_t = (uint32_t) sizeof(int16_t);
	c.t_int32_t = (uint32_t) sizeof(int32_t);
	c.t_int64_t = (uint32_t) sizeof(int64_t);

	return(files_write(p_file, &c, sizeof(c)));
}

static int catalog_check(void) {
	if(p_file == 0) {
		(void) set_error(EIO);

		LOGWARN(ERROR_SLIGHT, SUBSYSTEM,
			_("Failed to operate with catalog, it is not opened"));

		return(-1);
	}

	return(0);
}
