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

     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 <glib.h>

#include <msym.h>
#include <string.h>

#include "support.h"
#include "visu_tools.h"
#include "visu_basic.h"
#include "visu_data.h"
#include "sym.h"
#include "gtk_pick.h"
#include "gtk_main.h"
#include "extraGtkFunctions/gtk_numericalEntryWidget.h"

#define MSYM_DESCRIPTION _("<span size=\"smaller\">"			\
                           "This plug-in introduces support for\n"	\
                           "point group symmetry detection \n"		\
                           "thanks to <b>MSYM</b> library (see \n"       \
                           "<u><span color=\"blue\">http://github.com/mcodev31/libmsym</span></u>).</span>")
#define MSYM_AUTHORS     "Caliste Damien"

#define MSYM_INFO \
  _("left-button\t\t: select one atom to get the equivalent ones\n"	\
    "right-button\t\t: switch to observe")

/* Local methods */
static void onSymClicked(VisuMolSymmetry *symmetry, GtkWidget *source);

/* Local variables */
static gchar *iconPath;
static VisuMolSymmetry *symmetry = NULL;

/* Required methods for a loadable module. */
gboolean plugmsymInit()
{
  DBG_fprintf(stderr, "Msym: loading plug-in 'plugmsym'...\n");
  iconPath = g_build_filename(V_SIM_PIXMAPS_DIR, "msym.png", NULL);

  return TRUE;
}

static gboolean _toLblType(GBinding *bind _U_, const GValue *from,
                           GValue *to, gpointer data _U_)
{
  if (g_value_get_string(from))
    g_value_take_string(to, g_strdup_printf(_("point group symmetry: %s"),
                                            g_value_get_string(from)));
  else
    g_value_set_static_string(to, "");
  return TRUE;
}
static gboolean _toVisible(GBinding *bind _U_, const GValue *from,
                           GValue *to, gpointer data _U_)
{
  g_value_set_boolean(to, (g_value_get_string(from) && g_value_get_string(from)[0] != '\0'));
  return TRUE;
}
gboolean plugmsymInitGtk()
{
  GtkWidget *bt;
  
  DBG_fprintf(stderr, "Msym: create a symmetry object.\n");
  symmetry = visu_mol_symmetry_new();
  g_object_bind_property(visu_ui_interactive_pick_getSelection(), "model",
                         symmetry, "data", G_BINDING_SYNC_CREATE);
  g_object_bind_property(visu_ui_interactive_pick_getSelection(), "selection",
                         symmetry, "nodes", G_BINDING_SYNC_CREATE);

  bt = gtk_button_new_with_label("");
  gtk_button_set_relief(GTK_BUTTON(bt), GTK_RELIEF_NONE);
  gtk_box_pack_start(GTK_BOX(visu_ui_interactive_pick_getSelectionLabel()), bt, TRUE, FALSE, 0);
  gtk_widget_set_halign(bt, 0.5);
  g_object_bind_property_full(symmetry, "type", bt, "label",
                              G_BINDING_SYNC_CREATE,
                              _toLblType, NULL, (gpointer)0, (GDestroyNotify)0);
  g_object_bind_property_full(symmetry, "type", bt, "visible",
                              G_BINDING_SYNC_CREATE,
                              _toVisible, NULL, (gpointer)0, (GDestroyNotify)0);
  g_signal_connect_swapped(bt, "clicked", G_CALLBACK(onSymClicked), symmetry);

  return TRUE;
}

const char* plugmsymGet_description()
{
  return MSYM_DESCRIPTION;
}

const char* plugmsymGet_authors()
{
  return MSYM_AUTHORS;
}

const char* plugmsymGet_icon()
{
  return iconPath;
}

void plugmsymFree(void)
{
  if (symmetry)
    g_object_unref(symmetry);
}

static void _addThreshold(GtkBox *vbox, VisuMolSymmetry *symmetry,
                          const gchar *label, const gchar *property)
{
  GtkWidget *hbox, *wd;

  hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
  gtk_box_pack_start(vbox, hbox, FALSE, FALSE, 0);

  gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(label), FALSE, FALSE, 0);
  wd = visu_ui_numerical_entry_new(0.);
  gtk_entry_set_width_chars(GTK_ENTRY(wd), 6);
  g_object_bind_property(symmetry, property, wd, "value",
                         G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
  gtk_box_pack_end(GTK_BOX(hbox), wd, FALSE, FALSE, 0);
}

static void _removePlane(VisuPlane *plane)
{
  VisuGlNodeScene *scene;

  scene = visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering());
  if (scene)
    visu_plane_set_remove(visu_gl_node_scene_addPlanes(scene)->planes, plane);
}

static GtkWidget* _addSym(gpointer item, gpointer data _U_)
{
  GtkWidget *hbox, *wd;
  gchar *lbl;
  VisuPlane *plane;
  float normal[3];
  VisuMolSymmetryOp *op = VISU_MOL_SYMMETRY_OP(item);
  VisuGlNodeScene *scene;

  hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
  gtk_widget_set_margin_top(hbox, 2);
  gtk_widget_set_margin_bottom(hbox, 2);
  gtk_widget_set_margin_start(hbox, 10);
  gtk_widget_set_margin_end(hbox, 10);

  switch (visu_mol_symmetry_op_getType(op))
    {
    case OPERATION_IDENTITY:
      gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(_("Identity")), FALSE, FALSE, 0);
      break;
    case OPERATION_ROTATION:
      gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(_("Rotation")), FALSE, FALSE, 0);
      break;
    case OPERATION_ROTATION_REFLEXION:
      gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(_("Rotation + reflexion")), FALSE, FALSE, 0);
      break;
    case OPERATION_REFLEXION:
      gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(_("Reflexion")), FALSE, FALSE, 0);
      plane = visu_mol_symmetry_op_getReflexion(op);
      visu_plane_getNVectUser(plane, normal);
      lbl = g_strdup_printf(_("Plane (%4.2f ; %4.2f ; %4.2f)"),
                            normal[0], normal[1], normal[2]);
      wd = gtk_toggle_button_new_with_label(lbl);
      g_free(lbl);
      g_object_bind_property(plane, "rendered", wd, "active",
                             G_BINDING_SYNC_CREATE | G_BINDING_BIDIRECTIONAL);
      gtk_box_pack_end(GTK_BOX(hbox), wd, FALSE, FALSE, 0);
      scene = visu_ui_rendering_window_getGlScene(visu_ui_main_class_getDefaultRendering());
      visu_plane_set_add(visu_gl_node_scene_addPlanes(scene)->planes, plane);
      g_signal_connect_swapped(wd, "destroy", G_CALLBACK(_removePlane), plane);
      break;
    case OPERATION_INVERSION:
      gtk_box_pack_start(GTK_BOX(hbox), gtk_label_new(_("Inversion")), FALSE, FALSE, 0);
      break;
    }

  gtk_widget_show_all(hbox);

  return hbox;
}

static void _setHeader(GtkListBoxRow *row, GtkListBoxRow *before, gpointer data)
{
  gchar *hd, *type;
  guint n;
  GtkWidget *lbl;
  
  if (before)
    return;

  g_object_get(data, "n-symmetries", &n, "type", &type, NULL);
  hd = g_strdup_printf(_("<b>%d symmetries (%s)</b>"), n, type);
  lbl = gtk_label_new(hd);
  gtk_label_set_use_markup(GTK_LABEL(lbl), TRUE);
  gtk_widget_set_margin_top(lbl, 5);
  gtk_list_box_row_set_header(row, lbl);
  g_free(hd);
  g_free(type);
}

static void onSymClicked(VisuMolSymmetry *symmetry, GtkWidget *source)
{
  GtkWidget *pop, *vbox, *wd;

  pop = gtk_popover_new(source);
  gtk_popover_set_modal(GTK_POPOVER(pop), TRUE);

  vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
  gtk_container_add(GTK_CONTAINER(pop), vbox);
  gtk_container_set_border_width(GTK_CONTAINER(pop), 5);

  _addThreshold(GTK_BOX(vbox), symmetry,
                _("Geometry threshold:"), "threshold-geometry");
  _addThreshold(GTK_BOX(vbox), symmetry,
                _("Angle threshold:"), "threshold-angle");

  wd = gtk_list_box_new();
  gtk_box_pack_start(GTK_BOX(vbox), wd, TRUE, TRUE, 0);
  gtk_list_box_set_selection_mode(GTK_LIST_BOX(wd), GTK_SELECTION_MULTIPLE);
  gtk_list_box_bind_model(GTK_LIST_BOX(wd), G_LIST_MODEL(symmetry),
                          _addSym, (gpointer)0, (GDestroyNotify)0);
  gtk_list_box_set_header_func(GTK_LIST_BOX(wd), _setHeader,
                               symmetry, (GDestroyNotify)0);

  gtk_widget_show_all(pop);
}
