/*
 * options.c
 * 
 * Copyright (C) 2006  Josef Kufner <jk@myserver.cz>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "options.h"
#include "options-defaults.h"
#include "message.h"
#include "dirs.h"

#define DEBUG 0
#include "debug.h"

#define MAX_CAT_LEN	24
#define MAX_OPT_LEN	48


typedef struct {
	char cat[MAX_CAT_LEN], opt[MAX_OPT_LEN];
	OPTION_TYPE type;
	struct {
		char *string;
		int integer;
	} value;
} OPTION_ITEM;

int option_last_error = 0;

static OPTION_ITEM *option = NULL;
static int option_size = 1; /* half of initial size */
static int option_is_sorted = 0;
static OPTION_UPDATE_CALLBACK option_update_callback = NULL;

static const char *option_type_name[] = {
	"none",
	"integer",
	"string",
	NULL
};

static void option_enlarge(void)
{
	int old_size = option_size;
	option_size <<= 1;
	DBG_MSG(2, "option_enlarge: resizing array from %d to %d items", old_size, option_size);
	option = realloc(option, sizeof(OPTION_ITEM) * option_size);
	memset(option + old_size, 0, sizeof(OPTION_ITEM) * old_size);
	if (option == NULL) {
		perror("Option array realloc failed");
		abort();
	}
}


static int option_item_compare(const void *va, const void *vb)
{
	OPTION_ITEM *a = (OPTION_ITEM *)va;
	OPTION_ITEM *b = (OPTION_ITEM *)vb;
	int r;

	r = strcmp(a->cat, b->cat);
	return r != 0 ? r : strcmp(a->opt, b->opt);
}


static void option_sort(void)
{
	if (!option_is_sorted)
		qsort(option, option_size, sizeof(OPTION_ITEM), option_item_compare);
	option_is_sorted = 1;
}


static OPTION_ITEM *option_item_lookup(const char *cat, const char *opt)
{
	OPTION_ITEM key;
	strncpy(key.cat, cat, MAX_CAT_LEN - 1);
	strncpy(key.opt, opt, MAX_OPT_LEN - 1);
	key.cat[MAX_CAT_LEN - 1] = 0;
	key.opt[MAX_OPT_LEN - 1] = 0;
	
	DBG_MSG(4, "option_item_lookup: [ %s :: %s ]", key.cat, key.opt);

	option_sort();
	return (OPTION_ITEM *) bsearch(&key, option, option_size, sizeof(OPTION_ITEM), option_item_compare);
}


static OPTION_ITEM *option_item_add(const char *cat, const char *opt)
{
	OPTION_ITEM *a = NULL;
	
	DBG_MSG(4, "option_item_add: [ %s :: %s ]", cat, opt);

	if ((a = option_item_lookup(cat, opt)))
		return a;
	
	if (option[0].cat[0] == 0 && option[0].opt[0] == 0) {
		DBG_MSG(4, "option_item_add: have empty slot");
		a = &(option[0]);
	} else {
		DBG_MSG(4, "option_item_add: no empty slot");
		option_enlarge();
		a = &(option[option_size - 1]);
	}
	
	strncpy(a->cat, cat, MAX_CAT_LEN - 1);
	strncpy(a->opt, opt, MAX_OPT_LEN - 1);
	a->cat[MAX_CAT_LEN - 1] = 0;
	a->opt[MAX_OPT_LEN - 1] = 0;
	a->value.string = NULL;
	a->value.integer = 0;
	option_is_sorted = 0;
	return a;
}

static void option_item_reset(OPTION_ITEM *item) {
	assert(item != NULL);
	if (item->value.string) {
		free(item->value.string);
		item->value.string = NULL;
	}
	item->value.integer = 0;
	item->type = OPTION_NONE;
}


int option_init(void) {
	const struct s_options_defualts *p = NULL;

	DBG_MSG(1, "option_init");
	option_enlarge();
	memset(option, 0, sizeof(OPTION_ITEM) * option_size / 2);
	
	DBG_MSG(1, "option_init: Loading defaults...");
	for (p = options_defaults; p->opt; p++) {
		if (p->string)
			option_set_string("main", p->opt, p->string);
		else
			option_set_integer("main", p->opt, p->integer);
	}
	DBG_MSG(1, "option_init: Loading defaults... done.");
	
	return 1;
}


void option_set_update_callback(OPTION_UPDATE_CALLBACK callback)
{
	option_update_callback = callback;
}


static void option_run_update_callback(void)
{
	option_sort();
	if (option_update_callback)
		(*option_update_callback)();
}


int option_set_integer(const char *cat, const char *opt, int value)
{
	OPTION_ITEM *item = NULL;

	DBG_MSG(3, "option_set_integer: [ %s :: %s ] = %d", cat, opt, value);
	item = option_item_add(cat, opt);
	if (item) {
		option_item_reset(item);
		item->type = OPTION_INTEGER;
		item->value.integer = value;
		option_run_update_callback();
		return 1;
	}
	return 0;
}


int option_set_string(const char *cat, const char *opt, const char *value)
{
	OPTION_ITEM *item = NULL;

	DBG_MSG(3, "option_set_string: [ %s :: %s ] = \"%s\"", cat, opt, value);
	item = option_item_add(cat, opt);
	if (item) {
		option_item_reset(item);
		item->type = OPTION_STRING;
		item->value.string = strdup(value);
		option_run_update_callback();
		return 1;
	}
	return 0;
}


void option_unset_by_id(int id)
{
	DBG_MSG(4, "option_unset_by_id: id %d", id);
	if (option[id].cat[0]) {
		option_item_reset(&(option[id]));
		option[id].cat[0] = 0;
		option[id].opt[0] = 0;
		option_is_sorted = 0;
		option_run_update_callback();
	}
}


int option_unset(const char *cat, const char *opt)
{
	OPTION_ITEM *item = NULL;

	DBG_MSG(4, "option_unset: [ %s :: %s ]", cat, opt);
	item = option_item_lookup(cat, opt);
	if (item) {
		option_unset_by_id(item - option);
		return 1;
	}
	return 0;
}


int option_get_integer_by_id(int id)
{
	int v;

	if (option[id].type == OPTION_INTEGER) {
		DBG_MSG(4, "option_get_integer_by_id %d: %d", id, option[id].value.integer);
		return option[id].value.integer;
	} else if (option[id].type == OPTION_STRING) {
		v = atoi(option[id].value.string);
		DBG_MSG(4, "option_get_integer_by_id %d: \"%s\" => %d", id, option[id].value.string, v);
		return v;
	}
	return 0;
}


int option_get_integer(const char *cat, const char *opt)
{
	OPTION_ITEM *item;

	assert(cat != NULL);
	assert(opt != NULL);

	DBG_MSG(3, "option_get_integer: [ %s :: %s ]", cat, opt);
	item = option_item_lookup(cat, opt);
	if(item) {
		return option_get_integer_by_id(item - option);
	}
	return 0;
}


const char *option_get_string_by_id(int id)
{
	if (option[id].type == OPTION_INTEGER) {
		if (!option[id].value.string) {
			option[id].value.string = (char *) malloc(32);
			sprintf(option[id].value.string, "%d", option[id].value.integer);
		}
		DBG_MSG(4, "option_get_string by id %d: %d => \"%s\"", id, option[id].value.integer, option[id].value.string);
		return option[id].value.string;
	} else if (option[id].type == OPTION_STRING) {
		DBG_MSG(4, "option_get_string by id %d: \"%s\"", id, option[id].value.string);
		return option[id].value.string;
	}
	return NULL;
}


const char *option_get_string(const char *cat, const char *opt)
{
	OPTION_ITEM *item;

	assert(cat != NULL);
	assert(opt != NULL);

	DBG_MSG(3, "option_get_string: [ %s :: %s ]", cat, opt);
	item = option_item_lookup(cat, opt);
	if(item) {
		return option_get_string_by_id(item - option);
	}
	return NULL;
}


OPTION_TYPE option_get_type(const char *cat, const char *opt)
{
	OPTION_ITEM *item;

	assert(cat != NULL);
	assert(opt != NULL);

	DBG_MSG(4, "option_get_type: [ %s :: %s ]", cat, opt);
	item = option_item_lookup(cat, opt);
	if(item) {
		DBG_MSG(4, "option_get_type: [ %s :: %s ] is type %d", cat, opt, item->type);
		return item->type;
	}
	return OPTION_NONE;
}


const char *option_get_type_name_by_id(int id)
{
	return option_type_name[option[id].type];
}


const char *option_get_type_name(const char *cat, const char *opt)
{
	return option_type_name[option_get_type(cat, opt)];
}


int option_store_to_default(void)
{
	dir_update();
	return option_store_file(NULL, dir_main_config);
}
	
int option_store_file(const char *cat, const char *filename)
{
	FILE *f;

	DBG_MSG(1, "option_store_file: writing cat \"%s\" to file %s", cat, filename);
	assert(filename != NULL);
	
	f = fopen(filename, "wt");
	if (f) {
		option_store(cat, f, filename);
		if (fclose(f) != 0) {
			option_last_error = errno;
			perror(filename);
		}
		option_last_error = 0;
		return 1;
	} else {
		option_last_error = errno;
		perror(filename);
		return 0;
	}
}


int option_store(const char *cat, FILE *file, const char *filename_to_show)
{
	int i;
	char *str;
	MESSAGE *m = NULL;

	DBG_MSG(4, "option_store: cat = \"%s\", filename = \"%s\"", cat, filename_to_show);
	
	option_sort();

	for (i = 0; i < option_size; i++) {
		if (cat && strcmp(cat, option[i].cat) != 0)
			continue;

		if (!m)
			m = message_create('O', 0);

		if (option[i].type == OPTION_STRING)
			message_append(m, MESSAGE_STRING, "Os",
					MESSAGE_STRING, option[i].cat,
					MESSAGE_STRING, option[i].opt,
					MESSAGE_STRING, option[i].value.string,
					MESSAGE_END);
		else if (option[i].type == OPTION_INTEGER)
			message_append(m, MESSAGE_STRING, "Os",
					MESSAGE_STRING, option[i].cat,
					MESSAGE_STRING, option[i].opt,
					MESSAGE_INTEGER, option[i].value.integer,
					MESSAGE_END);
		else
			continue;

		str = message_to_string(m, 1);
		if (fputs(str, file) == EOF) {
			option_last_error = errno;
			perror(filename_to_show);
			free(str);
			break;
		}
		free(str);
		message_destroy(m);
		m = NULL;
	}
	if (m)
		message_destroy(m);
	option_last_error = 0;
	return 1;
}


int option_load_file(const char *filename)
{
	FILE *f;

	DBG_MSG(1, "option_load_file: loading file %s", filename);
	assert(filename != NULL);
	
	f = fopen(filename, "rt");
	if (f) {
		option_load(f, filename);
		if (fclose(f) != 0) {
			option_last_error = errno;
			perror(filename);
		}
		option_last_error = 0;
		return 1;
	} else {
		option_last_error = errno;
		perror(filename);
		return 0;
	}
}


int option_load(FILE *file, const char *filename_to_show)
{
	int ch, parsed, state = 0;
	MESSAGE *msg = NULL;
	GString *token = NULL;
	char *cmd = NULL;
	int err_showed = 0, msg_count = 0;
	
	DBG_MSG(4, "option_load: filename = \"%s\"", filename_to_show);
	
	while ((ch = getc(file)) != EOF) {
		parsed = message_from_stream('O', '?', ch, &state, &token, &msg);
		if (parsed == 1 && msg) {
			msg_count++;
			err_showed = 0;
			if (message_get(msg, MESSAGE_STRING, &cmd, MESSAGE_END) && cmd)
				message_edit(msg, 0, cmd[0]);
			message_send(msg);
			message_destroy(msg);
			msg = NULL;
		} else if (parsed == -1 && !err_showed) {
			fprintf(stderr, "%s: Syntax error after %d messages.\n", filename_to_show, msg_count);
			err_showed = 1;
		}
	}
	if (errno) {
		option_last_error = errno;
		perror(filename_to_show ? filename_to_show : "Can't read");
	}
	return 0;
}


int option_list_opt(const char *cat_query, int *iter, char **cat, char **opt)
{
	assert(iter != NULL);
	assert(opt != NULL);
	
	DBG_MSG(6, "option_list_opt: cat_query = %s, iter = %d", cat_query, *iter);
	while (cat_query && *iter < option_size && strcmp(cat_query, option[*iter].cat) != 0) {
		(*iter)++;
	}
	if (*iter < option_size) {
		*cat = option[*iter].cat;
		*opt = option[*iter].opt;
	} else {
		*cat = NULL;
		*opt = NULL;
	}
	return *iter < option_size;
}

