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

	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 COPYING.
*/
#include "legend.h"

#include <visu_configFile.h>
#include <openGLFunctions/objectList.h>
#include <openGLFunctions/text.h>

/**
 * SECTION:legend
 * @short_description: Draw a frame with the representation of each
 * atom species, its name and the number of elements.
 *
 * <para>This extension draws a frame on top of the rendering area with an
 * item per #VisuElement currently rendered. For each #VisuElement, a
 * small representation of its OpenGL shape is drawn, its label is
 * printed and the number of #VisuNode associated to this
 * element.</para>
 * <para>This extension defines one resource entry labeled
 * "legend_is_on" to control if the legend is printed or not.</para>
 *
 * Since: 3.5
 */

#define FLAG_RESOURCE_LEGEND_USED   "legend_is_on"
#define DESC_RESOURCE_LEGEND_USED   "Control if the legend is drawn ; boolean (0 or 1)"
static gboolean DEFAULT_LEGEND_USED = FALSE;

/**
 * VisuGlExtLegendClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuGlExtLegendClass structure.
 *
 * Since: 3.7
 */
/**
 * VisuGlExtLegend:
 *
 * An opaque structure.
 *
 * Since: 3.7
 */
/**
 * VisuGlExtLegendPrivate:
 *
 * Private fields for #VisuGlExtLegend objects.
 *
 * Since: 3.7
 */
struct _VisuGlExtLegendPrivate
{
  gboolean dispose_has_run;

  /* Legend definition. */
  VisuNodeArrayRenderer *nodes;
  gulong col_sig, mat_sig, pop_sig, siz_sig, ren_sig;
};
static VisuGlExtLegend* defaultLegend;

static void visu_gl_ext_legend_dispose(GObject* obj);
static void visu_gl_ext_legend_draw(const VisuGlExtFrame *legend);
static gboolean visu_gl_ext_legend_isValid(const VisuGlExtFrame *legend);
static void visu_gl_ext_legend_rebuild(VisuGlExt *ext);

/* Local callbacks. */
static void setDirty(VisuGlExt *ext);
static void onEntryUsed(VisuGlExtLegend *lg, VisuConfigFileEntry *entry, VisuConfigFile *obj);

/* Local routines. */
static void exportResources(GString *data, VisuData *dataObj);

G_DEFINE_TYPE_WITH_CODE(VisuGlExtLegend, visu_gl_ext_legend, VISU_TYPE_GL_EXT_FRAME,
                        G_ADD_PRIVATE(VisuGlExtLegend))

static void visu_gl_ext_legend_class_init(VisuGlExtLegendClass *klass)
{
  VisuConfigFileEntry *resourceEntry;

  DBG_fprintf(stderr, "Extension Legend: creating the class of the object.\n");
  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  DBG_fprintf(stderr, "                - adding new resources ;\n");
  resourceEntry = visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_RESOURCE,
                                                   FLAG_RESOURCE_LEGEND_USED,
                                                   DESC_RESOURCE_LEGEND_USED,
                                                   &DEFAULT_LEGEND_USED, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.5f);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_RESOURCE,
				   exportResources);

  defaultLegend = (VisuGlExtLegend*)0;

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_gl_ext_legend_dispose;
  VISU_GL_EXT_CLASS(klass)->rebuild = visu_gl_ext_legend_rebuild;
  VISU_GL_EXT_FRAME_CLASS(klass)->draw = visu_gl_ext_legend_draw;
  VISU_GL_EXT_FRAME_CLASS(klass)->isValid = visu_gl_ext_legend_isValid;
}

static void visu_gl_ext_legend_init(VisuGlExtLegend *obj)
{
  DBG_fprintf(stderr, "Extension Legend: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_gl_ext_legend_get_instance_private(obj);
  obj->priv->dispose_has_run = FALSE;

  /* Private data. */
  obj->priv->nodes = (VisuNodeArrayRenderer*)0;

  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_LEGEND_USED,
                          G_CALLBACK(onEntryUsed), (gpointer)obj, G_CONNECT_SWAPPED);

  if (!defaultLegend)
    defaultLegend = obj;
}

/* This method can be called several times.
   It should unref all of its reference to
   GObjects. */
static void visu_gl_ext_legend_dispose(GObject* obj)
{
  VisuGlExtLegend *legend;

  DBG_fprintf(stderr, "Extension Legend: dispose object %p.\n", (gpointer)obj);

  legend = VISU_GL_EXT_LEGEND(obj);
  if (legend->priv->dispose_has_run)
    return;
  legend->priv->dispose_has_run = TRUE;

  /* Disconnect signals. */
  visu_gl_ext_legend_setNodes(legend, (VisuNodeArrayRenderer*)0);

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_gl_ext_legend_parent_class)->dispose(obj);
}

/**
 * visu_gl_ext_legend_new:
 * @name: (allow-none): the name to give to the extension (default is #VISU_GL_EXT_LEGEND_ID).
 *
 * Creates a new #VisuGlExt to draw a legend.
 *
 * Since: 3.7
 *
 * Returns: a pointer to the #VisuGlExt it created or
 * NULL otherwise.
 */
VisuGlExtLegend* visu_gl_ext_legend_new(const gchar *name)
{
  char *name_ = VISU_GL_EXT_LEGEND_ID;
  char *description = _("Draw the name and the shape of available elements on screen.");
  VisuGlExt *legend;
#define LEGEND_HEIGHT 30

  DBG_fprintf(stderr,"Extension Legend: new object.\n");
  
  legend = VISU_GL_EXT(g_object_new(VISU_TYPE_GL_EXT_LEGEND,
                                    "active", DEFAULT_LEGEND_USED,
                                    "name", (name)?name:name_, "label", _(name),
                                    "description", description, "nGlObj", 1,
                                    "priority", VISU_GL_EXT_PRIORITY_LAST,
                                    "saveState", TRUE,
                                    "x-pos", 0.f, "y-pos", 1.f,
                                    "x-padding", 5.f, "y-padding", 3.f, NULL));
  visu_gl_ext_frame_setRequisition(VISU_GL_EXT_FRAME(legend), G_MAXUINT / 2, LEGEND_HEIGHT);

  return VISU_GL_EXT_LEGEND(legend);
}
/**
 * visu_gl_ext_legend_setNodes:
 * @legend: The #VisuGlExtLegend to attached to.
 * @nodes: the nodes to get the population of.
 *
 * Attach an #VisuGlView to render to and setup the legend to get the
 * node population also.
 *
 * Since: 3.7
 *
 * Returns: TRUE if model has been changed.
 **/
gboolean visu_gl_ext_legend_setNodes(VisuGlExtLegend *legend, VisuNodeArrayRenderer *nodes)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_LEGEND(legend), FALSE);

  if (legend->priv->nodes == nodes)
    return FALSE;

  if (legend->priv->nodes)
    {
      g_signal_handler_disconnect(G_OBJECT(legend->priv->nodes), legend->priv->ren_sig);
      g_signal_handler_disconnect(G_OBJECT(legend->priv->nodes), legend->priv->col_sig);
      g_signal_handler_disconnect(G_OBJECT(legend->priv->nodes), legend->priv->mat_sig);
      g_signal_handler_disconnect(G_OBJECT(legend->priv->nodes), legend->priv->pop_sig);
      g_signal_handler_disconnect(G_OBJECT(legend->priv->nodes), legend->priv->siz_sig);
      g_object_unref(legend->priv->nodes);
    }
  legend->priv->nodes = nodes;
  if (nodes)
    {
      g_object_ref(nodes);
      legend->priv->ren_sig =
        g_signal_connect_swapped(G_OBJECT(nodes), "element-notify::rendered",
                                 G_CALLBACK(setDirty), (gpointer)legend);
      legend->priv->col_sig =
        g_signal_connect_swapped(G_OBJECT(nodes), "element-notify::color",
                                 G_CALLBACK(setDirty), (gpointer)legend);
      legend->priv->mat_sig =
        g_signal_connect_swapped(G_OBJECT(nodes), "element-notify::material",
                                 G_CALLBACK(setDirty), (gpointer)legend);
      legend->priv->pop_sig =
        g_signal_connect_swapped(G_OBJECT(nodes), "nodes::population",
                                 G_CALLBACK(setDirty), (gpointer)legend);
      legend->priv->siz_sig =
        g_signal_connect_swapped(G_OBJECT(nodes), "element-size-changed",
                                 G_CALLBACK(setDirty), (gpointer)legend);
    }

  visu_gl_ext_setDirty(VISU_GL_EXT(legend), TRUE);
  return TRUE;
}
/**
 * visu_gl_ext_legend_getNodes:
 * @legend: a #VisuGlExtLegend object.
 *
 * @legend is displaying a label showing the element of a
 * #VisuNodeArray using the rendering properties of a #VisuNodeArrayRenderer.
 *
 * Since: 3.8
 *
 * Returns: (transfer none): the #VisuNodeArrayRenderer this legend is
 * based on.
 **/
VisuNodeArrayRenderer* visu_gl_ext_legend_getNodes(VisuGlExtLegend *legend)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_LEGEND(legend), (VisuNodeArrayRenderer*)0);
  return legend->priv->nodes;
}
static void onEntryUsed(VisuGlExtLegend *lg, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_ext_setActive(VISU_GL_EXT(lg), DEFAULT_LEGEND_USED);
}
static void setDirty(VisuGlExt *ext)
{
  visu_gl_ext_setDirty(ext, TRUE);
}

static void visu_gl_ext_legend_rebuild(VisuGlExt *ext)
{
  visu_gl_text_rebuildFontList();
  if (VISU_GL_EXT_GET_CLASS(ext)->draw)
    VISU_GL_EXT_GET_CLASS(ext)->draw(ext);
}

static gboolean visu_gl_ext_legend_isValid(const VisuGlExtFrame *frame)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_LEGEND(frame), FALSE);
  
  return (VISU_GL_EXT_LEGEND(frame)->priv->nodes != (VisuNodeArrayRenderer*)0);
}

static void visu_gl_ext_legend_draw(const VisuGlExtFrame *frame)
{
  guint dw;
  guint i;
  float scale, mSize;
  GString *str;
  VisuNodeArrayRendererIter iter;
  VisuGlExtLegend *legend;
  gboolean valid;

  g_return_if_fail(VISU_IS_GL_EXT_LEGEND(frame));
  legend = VISU_GL_EXT_LEGEND(frame);

  mSize = visu_node_array_renderer_getMaxElementSize(legend->priv->nodes, &i);
  DBG_fprintf(stderr, "Extension Legend: max size is %g (%d).\n", mSize, i);

  /* We draw the legend. */
  str = g_string_new("");
  scale = 0.5f * frame->height / mSize;
  dw = MAX(frame->width / i, frame->height + 10 + 60);
  for (valid = visu_node_array_renderer_iter_new(legend->priv->nodes, &iter, TRUE), i = 0;
       valid; valid = visu_node_array_renderer_iter_next(&iter), i += 1)
    {
      /* The element. */
      glEnable(GL_LIGHTING);
      if (visu_element_getRendered(iter.element))
        visu_element_renderer_colorize(iter.renderer, VISU_ELEMENT_RENDERER_NO_EFFECT);
      else
        visu_element_renderer_colorize(iter.renderer, VISU_ELEMENT_RENDERER_FLATTEN_DARK);
      glPushMatrix();
      glTranslated(0.5f * frame->height + i * dw, 0.5f * frame->height, 0.f);
      glRotated(45., 0, 0, 1);  
      glRotated(60., 0, 1, 0); 
      glScalef(scale, scale, scale);
      visu_element_renderer_call(iter.renderer);
      glPopMatrix();
      glDisable(GL_LIGHTING);

      /* The label. */
      glColor3fv(VISU_GL_EXT_FRAME(legend)->fontRGB);
      g_string_printf(str, "%s (%d)", visu_element_getName(iter.element), iter.nStoredNodes);
      glRasterPos2f(5.f + i * dw + frame->height, 5.f + 0.5f * (frame->height - 20));
      visu_gl_text_drawChars(str->str, VISU_GL_TEXT_SMALL);
    }
  g_string_free(str, TRUE);
}

static void exportResources(GString *data, VisuData *dataObj _U_)
{
  if (!defaultLegend)
    return;

  visu_config_file_exportComment(data, DESC_RESOURCE_LEGEND_USED);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_LEGEND_USED, NULL,
                               "%d", visu_gl_ext_getActive(VISU_GL_EXT(defaultLegend)));
  visu_config_file_exportComment(data, "");
}
