/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeur : Damien CALISTE,
	laboratoire L_Sim, (2001-2006)
  
	Adresse 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 : Damien CALISTE,
	laboratoire L_Sim, (2001-2006)

	E-mail address:
	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.
*/
#include <stdlib.h>
#include <stdio.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#include "dumpThroughGdkPixbuf.h"
#include <opengl.h>
#include <visu_tools.h>

static gpointer waitData;
static voidDataFunc waitFunc;


int writeViewInPngFormat(FileFormat *format, GString *buffer,
			 char* filename, int width, int height,
			 VisuData *dataObj,
			 voidDataFunc functionWait, gpointer data);
int writeViewInJpegFormat(FileFormat *format, GString *buffer,
			  char* filename, int width, int height,
			  VisuData *dataObj,
			  voidDataFunc functionWait, gpointer data);


DumpType* initDumpToPng()
{
  DumpType *png;
  char *typePng[] = {"*.png", (char*)0};
  FileFormat* fmt;

  png = malloc(sizeof(DumpType));
  if (!png)
    {
      allocationProblems();
      exit(1);
    }
  fmt = fileFormatNew(_("Png file"), typePng);
  if (!fmt)
    g_error("Can't initialize the Png dump module, aborting.\n");
  png->fileType = fmt;
  png->writeFunc = writeViewInPngFormat;
  
  waitFunc = (voidDataFunc)0;
  waitData = (gpointer)0;

  return png;
}

DumpType* initDumpToJpeg()
{
  DumpType *jpeg;
  char *typeJpeg[] = {"*.jpg", "*.jpeg", (char*)0};
  FileFormat* fmt;

  jpeg = malloc(sizeof(DumpType));
  if (!jpeg)
    {
      allocationProblems();
      exit(1);
    }
  fmt = fileFormatNew(_("Jpeg file"), typeJpeg);
  if (!fmt)
    g_error("Can't initialize the Jpeg dump module, aborting.\n");

  jpeg->fileType = fmt;
  jpeg->writeFunc = writeViewInJpegFormat;

  fileFormatAdd_propertyInteger(fmt, "quality", _("Compression ratio (given in percent)"), 85);
  
  waitFunc = (voidDataFunc)0;
  waitData = (gpointer)0;

  return jpeg;
}

int writeViewWithGdkPixbuf(FileFormat *format, GString *buffer,
			   char* filename, int width, int height, char* type,
			   VisuData *dataObj)
{
  unsigned char *image;
  GdkPixbuf *pixbuf;
  gboolean success;
  GError *error;
  GList *prop;
  char **propName, **propValues;
  int nb;

  image = dumpViewToImage(dataObj, buffer, &width, &height);
  if (!image)
    return 1;

  DBG_fprintf(stderr, "Dump with GdkPixbuf : begin %s export in %dx%d : %s.\n",
	      type, width, height, filename);

  pixbuf = gdk_pixbuf_new_from_data((guchar*)image,
				    GDK_COLORSPACE_RGB,
				    FALSE,
				    8,
				    width,
				    height,
				    3 * width,
				    NULL,
				    (gpointer)0);

  if (!pixbuf)
    {
      g_string_append(buffer, _("INTERNAL ERROR! Can't convert pixmap to pixbuf, aborting...\n"));
      free(image);
      return 1;
    }
  
  prop = fileFormatGet_propertiesList(format);
  nb = g_list_length(prop) + 1;
  propName = g_malloc(sizeof(char*) * nb);
  propValues = g_malloc(sizeof(char*) * nb);
  nb = 0;
  while (prop)
    {
      propName[nb] = g_strdup(fileFormatGet_propertyName((FileFormatProperty*)(prop->data)));
      switch (fileFormatGet_propertyType((FileFormatProperty*)(prop->data)))
	{
	case fileFormat_type_integer:
	  propValues[nb] =
	    g_strdup_printf("%d",
			    fileFormatGet_propertyInteger((FileFormatProperty*)(prop->data)));
	  break;
	default:
	  propValues[nb] = g_malloc(sizeof(char));
	};
      nb += 1;
      prop = g_list_next(prop);
    }
  propName[nb] = (char*)0;
  propValues[nb] = (char*)0;
  error = (GError*)0;
  success = gdk_pixbuf_savev(pixbuf, filename, type, propName, propValues, &error);
  g_strfreev(propName);
  g_strfreev(propValues);
  if (!success)
    {
      g_string_append(buffer, _("INTERNAL ERROR! Can't save pixbuf : "));
      g_string_append(buffer, error->message);
      gdk_pixbuf_unref(pixbuf);
      g_error_free(error);
      return 1;
    }
  free(image);
  gdk_pixbuf_unref(pixbuf);

  return 0;
}

int writeViewInJpegFormat(FileFormat *format, GString *buffer,
			  char* filename, int width, int height,
			  VisuData *dataObj,
			  voidDataFunc functionWait, gpointer data)
{
  int i, res;

  res = writeViewWithGdkPixbuf(format, buffer, filename, width, height, "jpeg", dataObj);

  /* Must call 100 times functionWait if exists before leaving... */
  if (functionWait)
    for (i = 0; i < 100; i++)
      functionWait(data);

  return res;
}

int writeViewInPngFormat(FileFormat *format, GString *buffer,
			 char* filename, int width, int height,
			 VisuData *dataObj,
			 voidDataFunc functionWait, gpointer data)
{
  int i, res;

  res = writeViewWithGdkPixbuf(format, buffer, filename, width, height, "png", dataObj);

  /* Must call 100 times functionWait if exists before leaving... */
  if (functionWait)
    for (i = 0; i < 100; i++)
      functionWait(data);

  return res;
}
