/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)
  
	Adresse mèl :
	BILLARD, non joignable par mèl ;
	CALISTE, damien P caliste AT cea P fr.

	Ce logiciel est un programme informatique servant à visualiser des
	structures atomiques dans un rendu pseudo-3D. 

	Ce logiciel est régi par la licence CeCILL soumise au droit français et
	respectant les principes de diffusion des logiciels libres. Vous pouvez
	utiliser, modifier et/ou redistribuer ce programme sous les conditions
	de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
	sur le site "http://www.cecill.info".

	Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
	pris connaissance de la licence CeCILL, et que vous en avez accepté les
	termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
	Copyright CEA, contributors : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2006)

	E-mail address:
	BILLARD, not reachable any more ;
	CALISTE, damien P caliste AT cea P fr.

	This software is a computer program whose purpose is to visualize atomic
	configurations in 3D.

	This software is governed by the CeCILL  license under French law and
	abiding by the rules of distribution of free software.  You can  use, 
	modify and/ or redistribute the software under the terms of the CeCILL
	license as circulated by CEA, CNRS and INRIA at the following URL
	"http://www.cecill.info". 

	The fact that you are presently reading this means that you have had
	knowledge of the CeCILL license and that you accept its terms. You can
	find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "visu_rendering.h"
#include "visu_data.h"
#include "renderingMethods/externalRenderingMethods.h"

#include "visu_object.h"
#include "visu_tools.h"
#include "visu_configFile.h"
#include "coreTools/toolFileFormat.h"

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


#define FLAG_FAV_RENDER    "rendering_favoriteMethod"
#define DESC_FAV_RENDER    "Favorite method used to render files ; chain"
#define DEFAULT_RENDER_FAV ""
gboolean readFavRenderingMethod(gchar **lines, int nbLines,
				int position, GString *errorMessage);
gboolean exportFavRenderingMethod(GString *data, int *nbLinesWritten);


/* A GHashTable to store all the available rendering methods
   in the system. The keys are the name of each method. */
GHashTable *availableRenderingMethod;

/* The list of the available rendering method. */
GList *listOfAvailableRenderingMethod;

/* A pointer to the in use rendering method. */
RenderingMethod *renderingMethodInUse;


/***************/
/* Public area */
/***************/

/* A method used by user to registered a new method. */
void registerRenderingMethod(RenderingMethod *method)
{
  DBG_fprintf(stderr, "Registering a new rendering method ... ");
  g_return_if_fail(method && method->name && method->name[0]);

  g_hash_table_insert(availableRenderingMethod, (gpointer)method->name, (gpointer)method);
  listOfAvailableRenderingMethod = g_list_append(listOfAvailableRenderingMethod,
						 method);
  
  DBG_fprintf(stderr, "'%s'\n", method->name);
}

GList* renderingMethodGet_AllMethods()
{
  return listOfAvailableRenderingMethod;
}

/* Free all the allocated attributes of the specified method. */
void renderingMethod_free(RenderingMethod* method)
{
  GList *tmpLst;
  int i;

  if (!method)
    return;
  if (method->name)
    free(method->name);
  if (method->printName)
    free(method->printName);
  if (method->description)
    free(method->description);
  if (method->fileType)
    {
      for (i = 0; i < method->nbFilesType; i++)
	{
	  tmpLst = method->fileType[i];
	  while(tmpLst)
	    {
	      fileFormatFree((FileFormat*)tmpLst->data);
	      tmpLst = g_list_next(tmpLst);
	    }
	}
      free(method->fileType);
    }
  free(method);
}

/* Allocate the structure and give values to all the attributes. */
RenderingMethod* renderingMethod_new(char* name, char* printName, char* description,
				     int nbFileType, renderingMethodLoadFunc loadMethod)
{
  RenderingMethod *method;
  int i;

  if (!name || !description || nbFileType < 0)
    {
      fprintf(stderr, "WARNING! 'renderingMethod' has just been called"
	      " with null parameters.\n");
      return (RenderingMethod*)0;
    }

  method = malloc(sizeof(RenderingMethod));
  if (!method)
    {
      allocationProblems();
      return (RenderingMethod*)0;
    }
  method->name = (char*)0;
  method->printName = (char*)0;
  method->description = (char*)0;
  method->icon = (char*)0;
  method->nbFilesType = nbFileType;
  method->fileTypeLabel = (gchar**)0;
  method->fileType = (GList**)0;
  method->loadMethod = (renderingMethodLoadFunc)0;
  method->createElement = (createOpenGLElementFunc)0;
  method->createNode = (createOpenGLNodeFunc)0;
  method->getExtensForElement = (getExtensOfNodeFunc)0;

  method->name = malloc(sizeof(char) * (strlen(name) + 1));
  if (!method->name)
    {
      allocationProblems();
      renderingMethod_free(method);
      return (RenderingMethod*)0;
    }
  strcpy(method->name, name);
  method->printName = g_strdup(printName);
  if (!method->printName)
    {
      allocationProblems();
      renderingMethod_free(method);
      return (RenderingMethod*)0;
    }
  method->description = malloc(sizeof(char) * (strlen(description) + 1));
  if (!method->description)
    {
      allocationProblems();
      renderingMethod_free(method);
      return (RenderingMethod*)0;
    }
  strcpy(method->description, description);
  method->loadMethod = loadMethod;
  method->fileType = malloc(sizeof(GList*) * nbFileType);
  if (!method->fileType)
    {
      allocationProblems();
      renderingMethod_free(method);
      return (RenderingMethod*)0;
    }
  for (i = 0; i < nbFileType; i++)
    method->fileType[i] = (GList*)0;
  method->fileTypeLabel = malloc(sizeof(GList*) * nbFileType);
  if (!method->fileTypeLabel)
    {
      allocationProblems();
      renderingMethod_free(method);
      return (RenderingMethod*)0;
    }

  return method;
}
int renderingMethodGet_nbFileType(RenderingMethod *method)
{
  if (!method)
    {
      fprintf(stderr, "WARNING! 'renderingMethodGet_nbFileType' has been called"
	      " with a null 'method'.\n");
      return -1;
    }
  return method->nbFilesType;
}

void renderingMethodSet_fileType(RenderingMethod *method, GList *fileTypeList,
				 int fileType, gchar* name)
{
  if (!method || fileType < 0 || fileType >= method->nbFilesType || !name)
    {
      fprintf(stderr, "WARNING! 'renderingMethodSet_fileType' has been called"
	      " with a null 'method' argument or 'fileType' is not between 0"
	      " and method->nbFilesType - 1.\n");
      return;
    }
  method->fileType[fileType] = fileTypeList;
  method->fileTypeLabel[fileType] = g_strdup(name);
}
GList* renderingMethodGet_fileType(RenderingMethod *method, int fileType)
{
  if (!method || fileType < 0 || fileType >= method->nbFilesType)
    {
      fprintf(stderr, "WARNING! 'renderingMethodGet_fileType' has been called"
	      " with a null 'method' argument or 'fileType' is not between 0"
	      " and method->nbFilesType - 1.\n");
      return (GList*)0;
    }
  return method->fileType[fileType];
}
gchar* renderingMethodGet_fileTypeName(RenderingMethod *method, int fileType)
{
  if (!method || fileType < 0 || fileType >= method->nbFilesType)
    {
      fprintf(stderr, "WARNING! 'renderingMethodGet_fileTypeName' has been called"
	      " with a null 'method' argument or 'fileType' is not between 0"
	      " and method->nbFilesType - 1.\n");
      return (gchar*)0;
    }
  return method->fileTypeLabel[fileType];
}
float renderingMethodGet_sizeOfElement(RenderingMethod *method, VisuElement *ele)
{
  g_return_val_if_fail(method && method->getExtensForElement && ele, 0.);

  return method->getExtensForElement(ele);
}


void renderingMethodSet_icon(RenderingMethod *method, char *path)
{
  if (!method)
    return;

  if (method->icon)
    {
      free(method->icon);
      method->icon = (char*)0;
    }
  if (!path)
    return;

  method->icon = malloc(sizeof(char) * (strlen(path) + 1));
  if (!method->icon)
    {
      allocationProblems();
      return;
    }
  strcpy(method->icon, path);
}

/* Choose the method used to render the data. */
void setRenderingMethodInUse(RenderingMethod* method)
{
  if (method == renderingMethodInUse)
    return;

  if (DEBUG)
    {
      if (method)
	{
	  DBG_fprintf(stderr, "Visu Rendering : set the rendering method to '%s' (%d).\n",
		      method->name, GPOINTER_TO_INT(method));
	}
      else
	{
	  DBG_fprintf(stderr, "Visu Rendering : set the rendering method to 'None' (%d).\n",
		      GPOINTER_TO_INT(method));
	}
    }
  renderingMethodInUse = method;
  g_signal_emit (visu, VISU_GET_CLASS (visu)->renderingChanged_signal_id,
		 0 , NULL);
}
int setRenderingMethodByName(char* name)
{
  RenderingMethod* method;

  method = g_hash_table_lookup(availableRenderingMethod, (gpointer)name);
  setRenderingMethodInUse(method);
  if (method)
    return 1;
  else
    return 0;
}
/* Get the current method used to render the data. */
RenderingMethod* getRenderingMethodInUse()
{
  return renderingMethodInUse;
}
/* This method allows to initiate the method
   to deal with the OpenGL methods. */
void setOpenGLMethods(RenderingMethod* method,
		      createOpenGLElementFunc createElement,
		      createOpenGLNodeFunc createNode,
		      getExtensOfNodeFunc getSize)
{
  if (!method)
    return;

  method->createElement = createElement;
  method->createNode = createNode;
  method->getExtensForElement = getSize;
}




/****************/
/* Private area */
/****************/

/* Initialise all the variable of this part. */
int initRenderingMethods()
{
  int i, res;
  RenderingMethod *meth;
  VisuConfigFileEntry *resourceEntry;

  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_PARAMETER,
					  FLAG_FAV_RENDER, DESC_FAV_RENDER,
					  1, readFavRenderingMethod);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_PARAMETER,
				   exportFavRenderingMethod);

  renderingMethodInUse = (RenderingMethod*)0;
  availableRenderingMethod = g_hash_table_new(g_str_hash, g_str_equal);
  listOfAvailableRenderingMethod = (GList*)0;

  g_return_val_if_fail(availableRenderingMethod, 0);

  res = 1;
  for (i = 0; listInitRendenringFunc[i]; i++)
    {
      meth = listInitRendenringFunc[i]();
      if (!meth)
	res = 0;
      registerRenderingMethod(meth);
    }
  
  if (!res)
    g_warning("Some rendering methods can't initialse.\n");

  DBG_fprintf(stderr, " %d valid rendering method(s) found.\n",
	      g_hash_table_size(availableRenderingMethod));

  return res;
}

/**************/
/* Parameters */
/**************/

gboolean readFavRenderingMethod(gchar **lines, int nbLines,
				int position, GString *errorMessage)
{
  int err;

  lines[0] = g_strstrip(lines[0]);

  if (!lines[0][0])
    setRenderingMethodInUse((RenderingMethod*)0);
  else
    {
      err = setRenderingMethodByName(lines[0]);
      if (!err)
	{
	  if (errorMessage)
	    g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
						   " the specified method (%s) is unknown.\n"),
				   position, lines[0]);
	  return FALSE;
	}
    }

  return TRUE;
}
gboolean exportFavRenderingMethod(GString *data, int *nbLinesWritten)
{
  g_string_append_printf(data, "# %s\n", DESC_FAV_RENDER);
  if (renderingMethodInUse)
    g_string_append_printf(data, "%s: %s\n\n", FLAG_FAV_RENDER, renderingMethodInUse->name);
  else
    g_string_append_printf(data, "%s:\n\n", FLAG_FAV_RENDER);

  *nbLinesWritten = 3;
  return TRUE;
}
