/*
 * ButtonBox - a program launcher
 *
 * Copyright (C) 2000 Paul Collins
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 *
 */

#define _GNU_SOURCE

#include "assertions.h"
#include "button.h"
#include "colour.h"
#include "configuration.h"

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

#include <X11/Xlib.h>
#include <X11/Xresource.h>

/* The configuration is a singleton object; that is, there is at most
   one of them in existence at any given moment.  Any attempt to
   create a new one will yield the existing instance. */



static char* do_xrm_query (XrmDatabase rdb, char** name, char** class);

static configuration* config_singleton = NULL;

button_info* lookup_button_info (XrmDatabase rdb, char* button);

static char* copy_value_to_string (XrmValue*);


configuration*
configuration_load_from_file (char* file_name)
{
	configuration* c = NULL;
	button_info* buttons = NULL;
	button_info* last = NULL;
	int num_buttons = 0;
	XrmDatabase rdb = NULL;
	char* rdb_type_return = NULL;
	XrmValue rdb_value_return;
	Bool rdb_status = False;
	char* rdb_button_list = NULL;
	char* token = NULL;
	
	if (config_singleton)
		return config_singleton;
	
	if (access (file_name, R_OK) != 0) {
		L ("configuration_load_from_file: %s: not readable\n",
		   file_name);
		return c;
	}
	L ("configuration_load_from_file: using file \"%s\"\n",
	   file_name);
	XrmInitialize ();
	rdb = XrmGetFileDatabase (file_name);
	I (rdb != NULL);

	/* Get the name for the default font. */
	{
		char* name_query[] = { "buttonbox.font", NULL };
		char* class_query[] = { "ButtonBox.Font", NULL };

		char* query_result = do_xrm_query (rdb, name_query, class_query);
		if (query_result) {
			button_set_default_font (query_result);
		}
		free (query_result);
	}

	/* Get the list of buttons.  If we fail, just return. */
	rdb_status = XrmGetResource (rdb, "buttonbox.buttonList", "Buttonbox.ButtonList",
				     &rdb_type_return, &rdb_value_return);
	if (!rdb_status) {
		L ("configuration_load_from_file: button list not present\n");
		XrmDestroyDatabase (rdb);
		return c;
	}
	rdb_button_list = copy_value_to_string (&rdb_value_return);
	L ("configuration_load_from_file: got '%s' for query on button list\n",
	   rdb_button_list);

	/* Tokenize the button list and retrieve their configuration. */
	token = strtok (rdb_button_list, " ");
	while (token != NULL) {
		button_info* b = lookup_button_info (rdb, token);
		/* Append it to the list of BIs. */
		if (b) {
			if (buttons == NULL) {
				buttons = b;
				last = b;
			} else {
				last->bi_next = b;
				last = b;
			}
			++num_buttons;
		} else {
			L("configuration_load_from_file: lookup_button_info: failed for "
			  "'%s'\n", token);
		}
		token = strtok (NULL, " ");
	}
	L ("configuration_load_from_file: got %d buttons\n", num_buttons);

	/* Build the configuration struct and return it. */
	c = malloc (sizeof (configuration));
	I (c != NULL);
	c->buttons = buttons;
	c->num_buttons = num_buttons;

	free (rdb_button_list);
	XrmDestroyDatabase (rdb);

	config_singleton = c;

	return c;
}



void
configuration_free (configuration* c)
{
	button_info* next = c->buttons;
	int i = 0;

	L ("configuration_free: %d button_info structs to free\n",
	   c->num_buttons);
	while (next != NULL) {
		button_info* current = next;
		free (current->bi_text);
		free (current->bi_command);
		next = current->bi_next;
		free (current);
		++i;
	}
	if (i != c->num_buttons) {
		L ("configuration_free: c->num_buttons = %d, but %d were freed\n",
		   c->num_buttons, i);
	}
	free (c);
}



button_info*
lookup_button_info (XrmDatabase rdb, char* button)
{
	button_info* b = NULL;
	char* name_query_comps[4] = { "buttonbox.buttons.", NULL, NULL, NULL };
	char* class_query_comps[3] = { "ButtonBox.Buttons.Button", NULL, NULL };
	char* query_result = NULL;
	unsigned long pixel = 0;
	
	I (rdb != NULL);
	I (button != NULL);
	b = malloc (sizeof (button_info));
	I (b != 0);
	
	/* Query for the button's title. */
	name_query_comps[1] = button;
	name_query_comps[2] = ".title";
	class_query_comps[1] = ".Title";
	query_result = do_xrm_query (rdb, name_query_comps, class_query_comps);
	if (query_result) {
		b->bi_text = query_result;
		L ("lookup_button_info: got title for button '%s'\n", button);
	} else {
		L ("lookup_button_info: no match for title for button '%s'; using '%s'\n",
		   button, button);
		b->bi_text = strdup (button);
		I (b->bi_text != NULL);
	}

	/* Query for the button's command. */
	name_query_comps[2] = ".command";
	class_query_comps[1] = ".Command";
	query_result = do_xrm_query (rdb, name_query_comps, class_query_comps);
	if (query_result) {
		b->bi_command = query_result;
		L ("lookup_button_info: got command for button '%s'\n", button);
	} else {
		L ("lookup_button_info: no match for command for button '%s'; using '%s'\n",
		   button, "/bin/false");
		b->bi_command = strdup ("/bin/false");
		I (b->bi_command != NULL);
	}
	b->bi_next = NULL;
	
	name_query_comps[2] = ".foreground";
	class_query_comps[1] = ".Foreground";
	query_result = do_xrm_query (rdb, name_query_comps, class_query_comps);
	if (query_result) {
		if (colour_allocate (query_result, &pixel)) {
			L ("lookup_button_info: foreground color \"%s\" allocated\n",
			   query_result);
			b->bi_foreground_pixel = pixel;
		} else {
			L ("lookup_button_info: foreground color \"%s\" NOT allocated; "
			   "using BlackPixel\n", query_result);
			b->bi_foreground_pixel = colour_get_black_pixel ();
		}
		free (query_result);
	} else {
		b->bi_foreground_pixel = colour_get_black_pixel ();
	}
			
	name_query_comps[2] = ".background";
	class_query_comps[1] = ".Background";
	query_result = do_xrm_query (rdb, name_query_comps, class_query_comps);
	if (query_result) {
		if (colour_allocate (query_result, &pixel)) {
			L ("lookup_button_info: background color \"%s\" allocated\n",
			   query_result);
			b->bi_background_pixel = pixel;
		} else {
			L ("lookup_button_info: background color \"%s\" NOT allocated; "
			   "using WhitePixel\n", query_result);
			b->bi_background_pixel = colour_get_white_pixel ();
		}
		free (query_result);
	} else {
		b->bi_background_pixel = colour_get_white_pixel ();
	}

	name_query_comps[2] = ".borderColor";
	class_query_comps[1] = ".BorderColor";
	query_result = do_xrm_query (rdb, name_query_comps, class_query_comps);
	if (query_result) {
		if (colour_allocate (query_result, &pixel)) {
			L ("lookup_button_info: border color \"%s\" allocated\n",
			   query_result);
			b->bi_border_pixel = pixel;
		} else {
			L ("lookup_button_info: border color \"%s\" NOT allocated; "
			   "using BlackPixel\n", query_result);
			b->bi_border_pixel = colour_get_black_pixel ();
		}
		free (query_result);
	} else {
		b->bi_border_pixel = colour_get_black_pixel ();
	}
	
	return b;
}



static char*
do_xrm_query (XrmDatabase rdb, char** name, char** class)
{
	char* name_query = NULL;
	char* class_query = NULL;
	int i = 0;
	int len = 0;
	Bool query_success = False;
	XrmValue value_return;
	char* type_return = NULL;
	char* r = NULL;
	
	for (i = 0, len = 0; name[i] != NULL; ++i) {
		I (name[i] != NULL);
		len += strlen (name[i]);
	}
	name_query = malloc (len + 1);
	I (name_query != NULL);
	strcpy (name_query, name[0]);
	for (i = 1; name[i] != NULL; ++i) {
		I (name[i] != NULL);
		strcat (name_query, name[i]);
	}
	L ("do_xrm_query: name_query is \"%s\"\n", name_query);
	
	for (i = 0, len = 0; class[i] != NULL; ++i) {
		I (class[i] != NULL);
		len += strlen (class[i]);
	}
	class_query = malloc (len + 1);
	I (class_query != NULL);
	strcpy (class_query, class[0]);
	for (i = 1; class[i] != NULL; ++i) {
		I (class[i] != NULL);
		strcat (class_query, class[i]);
	}
	L ("do_xrm_query: class_query is \"%s\"\n", class_query);

	query_success = XrmGetResource (rdb, name_query, class_query,
					&type_return, &value_return);

	free (name_query);
	free (class_query);
	if (query_success) {
		r = copy_value_to_string (&value_return);
		L ("do_xrm_query: query succeeded, returned \"%s\"\n", r);
	} else {
		L ("do_xrm_query: query failed, returned NULL\n");
	}
	
	
	return r;
}



static char*
copy_value_to_string (XrmValue* v)
{
	char* r = NULL;
	
	r = malloc (v->size + 1);
	I (r != NULL);
	memcpy (r, v->addr, v->size);
	r[v->size] = '\0';
	
	return r;
}

