/*******************************************\
| * Ce programme est sous liscence GNU GPL  * |
| * This software is under GNU/GPL licence  * |
| * * * * * * * * * * * * * * * * * * * * * * |
| * http://www.gnu.org/copyleft/gpl.html    * |
 \*******************************************/

/* Cr er par Laurent Coustet <ed@zehome.com>
 * http://ed.zehome.com/                    
 * Made by Laurent Coustet <ed@zehome.com>
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>

#include "templates.h"
#include "debug.h"
#include "edblog.h"

/* for template parsing, you must define a search symbol */
#ifndef TPL_SYB
#define TPL_SYB "ø"
#endif

#define ENTRY_DELIM "¬¬¬¬"
#define ENTRIES_DELIM "$}"

unsigned char *_tpl_file_head;
unsigned char *_tpl_file_body;
unsigned char *_tpl_file_tail;

varval_st  *liste=NULL;

void init_blog (unsigned char *_head_file, unsigned char *_body_file, unsigned char *_tail_file)
{
  _tpl_file_head = _head_file;
  _tpl_file_body = _body_file;
  _tpl_file_tail = _tail_file;

  liste = add_tpl_value (liste, "%titre", "Le Blog de Laurent Coustet (ed).\n");

  return;
}

void draw_head (FILE *out)
{
  parse_template (liste, out, _tpl_file_head);
}

void draw_tail (FILE *out)
{
  parse_template (liste, out, _tpl_file_tail);
}

void draw_blog (FILE *out, char *blogfile)
{
  FILE *blog_ptr_file;
  int i=0;
  char *temp_buf;
  char *read_buf;
  char *entry;
  int size=0;

  if ( (blog_ptr_file = fopen (blogfile,"r")) == NULL)
    {
      printf("Impossible d'ouvrir %s\n",blogfile);
      ERROR ("Impossible to open %s in \"r\"\n",blogfile);
      //exit (1);
      return;
    }

  fseek (blog_ptr_file, 0, SEEK_END);
  size = ftell (blog_ptr_file);
  fseek (blog_ptr_file, 0, SEEK_SET);

  read_buf = malloc(size);

  fread (read_buf, sizeof (char), size, blog_ptr_file);

  temp_buf = malloc(size);
  entry = malloc(size);

  strcpy (entry, read_buf);

  while ((strstr (read_buf,ENTRY_DELIM)) != NULL )
    {
      i++;
      strcpy (entry, read_buf);
      strtok (entry,ENTRY_DELIM);

      strcpy (temp_buf,entry);
      strtok (temp_buf,ENTRIES_DELIM);
      liste = add_tpl_value (liste, "entry.date",temp_buf);

      temp_buf = strtok (NULL,ENTRIES_DELIM);
      liste = add_tpl_value (liste, "entry.titre",temp_buf);

      temp_buf = strtok (NULL,ENTRIES_DELIM);
      liste = add_tpl_value (liste, "entry.body",temp_buf);

      parse_template (liste,out,_tpl_file_body);

      liste = del_tpl_var (liste, "entry.date");
      liste = del_tpl_var (liste, "entry.titre");
      liste = del_tpl_var (liste, "entry.body");

      read_buf += strlen(entry) + strlen(ENTRY_DELIM);

    }
  return;
}