/*
 * dsyslog - a dumb syslog (e.g. syslog for people who have a clue)
 * Copyright (c) 2008 William Pitcock <nenolod@sacredspiral.co.uk>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice is present in all copies.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "dsyslog.h"

dsyslog_template_t* dsyslog_template_new(char* template_string)
{
	dsyslog_template_t *t_template = g_slice_new0(dsyslog_template_t);
	t_template->template_string = g_malloc0(strlen(template_string) * 2);
	g_strlcpy(t_template->template_string, template_string, strlen(template_string) * 2);

	return t_template;
}

void dsyslog_template_associate_str(dsyslog_template_t* template, char* key, char* string)
{
	
	dsyslog_template_value_t* temp = g_slice_new0(dsyslog_template_value_t);
	
	temp->key = g_malloc0(strlen(key)*2);
	temp->value = g_malloc0(strlen(string)*2);
	
	g_strlcpy(temp->key, key, strlen(key)*2);
	g_strlcpy(temp->value, string, strlen(string)*2);
	
	template->keywords = g_list_prepend(template->keywords, temp);
	
}
void dsyslog_template_associate_int(dsyslog_template_t* template, char* key, int number)
{
	int size = (log10(number) +1);
	char* temp = g_malloc0( size * sizeof(char));
	temp = g_snprintf("%i", size, number);
	
	dsyslog_template_associate_str(template, key, temp);
	
	g_free(temp); 
	
}

char* __dsyslog_template_strr(char *stack, char *needle, char *repl)
{
      int needle_len, repl_len;
      char *p, *q;

      if(NULL == (p = strstr(stack, needle))) return p;
      needle_len = strlen(needle);
      repl_len = strlen(repl);
      memmove(q = p+repl_len, p+needle_len, strlen(p+needle_len)+1);
      memcpy(p, repl, repl_len);
      return q;
}

GChar* dsyslog_template_eval(dsyslog_template_t* template)
{
	GList* n, n2;
	
	for(n = template->keywords, n2 = g_list_next(n); n!=NULL; n = n2, n2 =g_list_next(n2)) 
	{
		while((template->template_string = __dsyslog_template_strr(template->template_string, n->data->key, n->data)) != NULL);
	}
	
	return template->template_string;
	// trashes the template
}