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

	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.
*/

#define _ISOC99_SOURCE

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

#include "atomic_yaml.h"

#include <coreTools/atoms_yaml.h>
#include <coreTools/toolFileFormat.h>
#include <extraFunctions/floatProp.h>
#include <extraFunctions/vectorProp.h>
#include <extraFunctions/fragProp.h>
#include <extraFunctions/poleProp.h>
#include <visu_dataloadable.h>
#include <visu_dataatomic.h>
#include <renderingMethods/elementAtomic.h>

#ifdef HAVE_YAML
static VisuDataLoader *yamlLoader = NULL;

static gboolean loadYaml(VisuDataLoader *self, VisuDataLoadable *data,
                         guint iType, guint nSet,
                         GCancellable *cancel, GError **error);
#endif

/**
 * SECTION:atomic_yaml
 * @short_description: Method to load YAML position file.
 *
 * <para>YAML format is a plain text format to store atomic
 * positions. This format is defined and used by BigDFT. It has
 * meta-data available to store forces, total energy, units, boundary
 * conditions...</para>
 */

/**
 * visu_data_loader_yaml_getStatic:
 *
 * Retrieve the instance of the atomic loader used to parse YAML files.
 *
 * Since: 3.8
 *
 * Returns: (transfer none): a #VisuDataLoader owned by V_Sim.
 **/
VisuDataLoader* visu_data_loader_yaml_getStatic(void)
{
#ifdef HAVE_YAML
  const gchar *typeYAML[] = {"*.yaml", (char*)0};

  if (yamlLoader)
    return yamlLoader;

  return yamlLoader = visu_data_loader_new(_("BigDFT YAML format"), typeYAML,
                                           FALSE, loadYaml, 110);
#else
  g_message("No YAML support.");

  return (VisuDataLoader*)0;
#endif
}

static void _setNodeProp(VisuData *data, VisuNode *node,
                                const PosinpDict *dict)
{
  guint j, k;
  VisuNodeValues *vals;
  GValue valI = G_VALUE_INIT;
  GValue valF = G_VALUE_INIT;
  GValue valS = G_VALUE_INIT;
  GValue valP = G_VALUE_INIT;
  gfloat *farr;

  if (!dict)
    return;

  g_value_init(&valI, G_TYPE_INT);
  g_value_init(&valF, G_TYPE_FLOAT);
  g_value_init(&valS, G_TYPE_STRING);
  g_value_init(&valP, G_TYPE_POINTER);
  for (j = 0; dict->items && dict->items[j].key && j < dict->len; j++)
    {
      if (!strcmp(dict->items[j].key, "frag"))
        vals = visu_data_getNodeProperties(data, _("Fragment"));
      else
        vals = visu_data_getNodeProperties(data, dict->items[j].key);
      if (!vals)
        {
          switch (dict->items[j].type)
            {
            case POSINP_TYPE_INT:
              vals = visu_node_values_new(VISU_NODE_ARRAY(data),
                                          dict->items[j].key, G_TYPE_INT, 1);
              break;
            case POSINP_TYPE_DBL:
              vals = VISU_NODE_VALUES
                (visu_node_values_farray_new(VISU_NODE_ARRAY(data),
                                             dict->items[j].key, 1));
              break;
            case POSINP_TYPE_STR:
              vals = visu_node_values_new(VISU_NODE_ARRAY(data),
                                          dict->items[j].key, G_TYPE_STRING, 1);
              break;
            case POSINP_TYPE_DBL_ARR:
              if (dict->items[j].value.darr.len == 3)
                vals = VISU_NODE_VALUES
                  (visu_node_values_vector_new(VISU_NODE_ARRAY(data),
                                               dict->items[j].key));
              else
                vals = VISU_NODE_VALUES
                  (visu_node_values_farray_new(VISU_NODE_ARRAY(data),
                                               dict->items[j].key,
                                               dict->items[j].value.darr.len));
              break;
            case POSINP_TYPE_DICT:
              if (!strcmp(dict->items[j].key, "frag"))
                vals = VISU_NODE_VALUES
                  (visu_node_values_frag_new(VISU_NODE_ARRAY(data),
                                             _("Fragment")));
              break;
            default:
              vals = (VisuNodeValues*)0;
              break;
            }
          if (vals && !visu_data_addNodeProperties(data, vals))
            g_warning("Cannot add node property '%s'.", visu_node_values_getLabel(vals));
        }
      if (!vals)
        continue;

      switch (dict->items[j].type)
        {
        case POSINP_TYPE_INT:
          g_value_set_int(&valI, dict->items[j].value.ival);
          visu_node_values_setAt(vals, node, &valI);
          break;
        case POSINP_TYPE_DBL:
          g_value_set_float(&valF, dict->items[j].value.dval);
          visu_node_values_setAt(vals, node, &valF);
          break;
        case POSINP_TYPE_STR:
          g_value_set_static_string(&valS, dict->items[j].value.str);
          visu_node_values_setAt(vals, node, &valS);
          break;
        case POSINP_TYPE_DBL_ARR:
          if (VISU_IS_NODE_VALUES_VECTOR(vals))
            visu_node_values_vector_setAtDbl
              (VISU_NODE_VALUES_VECTOR(vals), node, dict->items[j].value.darr.arr);
          else
            {
              farr = g_malloc0(sizeof(float) *
                               visu_node_values_getDimension(vals));
              g_value_set_pointer(&valP, farr);
              if (visu_node_values_getDimension(vals) ==
                  dict->items[j].value.darr.len)
                for (k = 0; k < dict->items[j].value.darr.len; k++)
                  farr[k] = dict->items[j].value.darr.arr[k];
              visu_node_values_setAt(vals, node, &valP);
              g_free(farr);
            }
          break;
        case POSINP_TYPE_DICT:
          if (VISU_IS_NODE_VALUES_FRAG(vals) &&
              dict->items[j].value.dict.len >= 2 &&
              dict->items[j].value.dict.items[0].key &&
              dict->items[j].value.dict.items[0].type == POSINP_TYPE_STR &&
              dict->items[j].value.dict.items[1].key &&
              dict->items[j].value.dict.items[1].type == POSINP_TYPE_INT)
            {
              VisuNodeFragment frag;
              frag.label = dict->items[j].value.dict.items[0].value.str;
              frag.id    = dict->items[j].value.dict.items[1].value.ival;
              visu_node_values_frag_setAt(VISU_NODE_VALUES_FRAG(vals), node, &frag);
            }
          break;
        default:
          break;
        }
    }
}

/**
 * visu_data_loader_yaml_setNodeProp:
 * @data: a #VisuData object.
 * @node: a #VisuNode structure.
 * @yamlStr: a YAML string.
 *
 * Parse @yamlStr and create #VisuNodeValues properties on @node.
 *
 * Since: 3.8
 **/
void visu_data_loader_yaml_setNodeProp(VisuData *data, VisuNode *node,
                                       const gchar *yamlStr)
{
  PosinpDict *dict;

  dict = posinp_yaml_parse_properties(yamlStr, (char**)0);
  _setNodeProp(data, node, dict);
  posinp_yaml_free_properties(dict);
}

#ifdef HAVE_YAML
static gboolean loadYaml(VisuDataLoader *self _U_, VisuDataLoadable *data,
                         guint iType, guint nSet,
                         GCancellable *cancel _U_, GError **error)
{
  gchar *dirname, *def;
  PosinpList *lst, *tmp;
  PosinpAtoms *atoms;
  guint nSets, i;
  GArray *types, *nattyp;
  VisuElement *type;
  double boxGeometry[6];
  float xyz[3], uvw[3], fxyz[3];
  GArray *forces;
  char *message;
  VisuBox *box;
  VisuNodeValuesString *labels;
  VisuNodeValues *igspin, *igchg;
  GValue ig = G_VALUE_INIT;

  g_return_val_if_fail(error && *error == (GError*)0, FALSE);

  message = (char*)0;
  lst = (PosinpList*)0;
  /* Start by looking for a default.yaml file. */
  dirname = g_path_get_dirname(visu_data_loadable_getFilename(data, iType));
  def = g_build_filename(dirname, "default.yaml", NULL);
  g_free(dirname);
  posinp_yaml_parse(&lst, def, (char**)0);
  if (DEBUG) for (nSets = 0, tmp = lst; tmp; tmp = tmp->next, nSets ++);
  DBG_fprintf(stderr, "Atomic YAML: default.yaml has %d documents (%d atoms).\n",
              nSets, (lst && lst->data) ? (int)lst->data->nat : -1);
  g_free(def);
  /* Overload with the given file. */
  posinp_yaml_parse(&lst, visu_data_loadable_getFilename(data, iType), &message);
  if (!lst)
    {
      if (message)
        free(message);
      return FALSE;
    }
  
  if (DEBUG) for (nSets = 0, tmp = lst; tmp; tmp = tmp->next, nSets ++);
  DBG_fprintf(stderr, "Atomic YAML: loading '%s' as a YAML file (%d documents).\n",
              visu_data_loadable_getFilename(data, iType), nSets);
  for (nSets = 0, tmp = lst; tmp && nSets < (guint)nSet; tmp = tmp->next)
    nSets += 1;
  DBG_fprintf(stderr, " | found atoms at %p.\n", (gpointer)tmp);
  if (tmp && tmp->data && tmp->data->nat > 0)
    atoms = tmp->data;
  else
    {
      DBG_fprintf(stderr, "Atomic YAML: failing with nat = %d.\n",
                  (tmp && tmp->data)?(int)tmp->data->nat:-1);
      if (message)
        free(message);
      posinp_yaml_free_list(lst);
      return FALSE;
    }
  DBG_fprintf(stderr, " | found %d atoms.\n", (atoms)?(int)atoms->nat:-1);
  if (message)
    {
      /* We don't have next tmp so the message is for us. */
      if (!tmp->next)
        {
          *error = g_error_new(VISU_DATA_LOADABLE_ERROR, DATA_LOADABLE_ERROR_FORMAT,
                               "%s", message);
          free(message);
          posinp_yaml_free_list(lst);
          return TRUE;
        }
      else
        free(message);
    }

  /* Counting the number of sets. */
  nSets = 0;
  for (tmp = lst; tmp; tmp = tmp->next)
    nSets += 1;
  visu_data_loadable_setNSets(data, nSets);

  /* Set comments. */
  for (tmp = lst, i = 0; tmp; tmp = tmp->next, i++)
    visu_data_loadable_setSetLabel(data, tmp->data->comment, i);
  /* Set metadata. */
  if (!isnan(atoms->energy))
    switch (atoms->eunits)
      {
      case (POSINP_ENERG_UNITS_HARTREE):
        g_object_set(G_OBJECT(data), "totalEnergy", atoms->energy * 27.2113834, NULL);
        break;
      case (POSINP_ENERG_UNITS_RYDBERG):
        g_object_set(G_OBJECT(data), "totalEnergy", atoms->energy * 0.5 * 27.2113834, NULL);
        break;
      case (POSINP_ENERG_UNITS_EV):
      default:
        g_object_set(G_OBJECT(data), "totalEnergy", atoms->energy, NULL);
        break;
    }

  /* Setup the population. */
  types  = g_array_sized_new(FALSE, FALSE, sizeof(VisuElement*), atoms->ntypes);
  for (i = 0; i < atoms->ntypes; i++)
    {
      type = visu_element_retrieveFromName(atoms->atomnames[i], (gboolean*)0);
      g_array_append_val(types, type);
    }
  nattyp = g_array_sized_new(FALSE, TRUE, sizeof(guint), atoms->ntypes);
  g_array_set_size(nattyp, atoms->ntypes);
  for (i = 0; i < atoms->nat;  i++)
    *(&g_array_index(nattyp, guint, atoms->iatype[i])) += 1;
  visu_node_array_allocate(VISU_NODE_ARRAY(data), types, nattyp);
  DBG_fprintf(stderr, "Atomic YAML: there are %d types in this file.\n", atoms->ntypes);
  if (DEBUG)
    {
      for (i = 0; i < atoms->ntypes; i++)
	DBG_fprintf(stderr, " | %d atom(s) for type %d.\n",
                    g_array_index(nattyp, guint, i), i);
    }
  g_array_free(nattyp, TRUE);
  g_array_free(types, TRUE);

  if (sin(atoms->angdeg[2]) == 0.f)
    {
      *error = g_error_new(VISU_DATA_LOADABLE_ERROR, DATA_LOADABLE_ERROR_FORMAT,
                           _("Wrong (ab) angle, should be"
                             " different from 0[pi].\n\n"
                             " Quoting '%g'.\n"), atoms->angdeg[2]);
      posinp_yaml_free_list(lst);
      return TRUE;
    }

  /* We remove the infinity. */
  if (!(atoms->BC & 1))
    atoms->acell[2] = 1.;
  if (!(atoms->BC & 2))
    atoms->acell[1] = 1.;
  if (!(atoms->BC & 4))
    atoms->acell[0] = 1.;

  boxGeometry[0] = atoms->acell[0];
  boxGeometry[1] = atoms->acell[1] * cos(G_PI * atoms->angdeg[2] / 180.);
  boxGeometry[2] = atoms->acell[1] * sin(G_PI * atoms->angdeg[2] / 180.);
  boxGeometry[3] = atoms->acell[2] * cos(G_PI * atoms->angdeg[1] / 180.);
  boxGeometry[4] = atoms->acell[2] * (cos(G_PI * atoms->angdeg[0] / 180.) -
                                      cos(G_PI * atoms->angdeg[1] / 180.) *
                                      cos(G_PI * atoms->angdeg[2] / 180.)) /
    sin(G_PI * atoms->angdeg[2] / 180.);
  boxGeometry[5] = sqrt(atoms->acell[2] * atoms->acell[2] -
                        boxGeometry[3] * boxGeometry[3] -
                        boxGeometry[4] * boxGeometry[4]);
  boxGeometry[5] *= (atoms->angdeg[1] < 0.)?-1.:+1.;

  /* Always set the given box, in case coordinates are reduced. */
  box = (VisuBox*)0;
  switch (atoms->BC)
    {
    case (POSINP_BC_PERIODIC):
      box = visu_box_new(boxGeometry, VISU_BOX_PERIODIC);
      break;
    case (POSINP_BC_FREE):
      box = visu_box_new(boxGeometry, VISU_BOX_FREE);
      break;
    case (POSINP_BC_SURFACE_XZ):
      box = visu_box_new(boxGeometry, VISU_BOX_SURFACE_ZX);
      break;
    default:
      *error = g_error_new(VISU_DATA_LOADABLE_ERROR, DATA_LOADABLE_ERROR_FORMAT,
                           _("Unsupported boundary conditions.\n"));
      posinp_yaml_free_list(lst);
      return TRUE;
    }
  visu_boxed_setBox(VISU_BOXED(data), VISU_BOXED(box));
  g_object_unref(box);

  for (i = 0; i < atoms->nat; i++)
    {
      xyz[0] = uvw[0] = (float)atoms->rxyz[3 * i + 0];
      xyz[1] = uvw[1] = (float)atoms->rxyz[3 * i + 1];
      xyz[2] = uvw[2] = (float)atoms->rxyz[3 * i + 2];
      if (atoms->units == POSINP_COORD_UNITS_REDUCED)
        visu_box_convertBoxCoordinatestoXYZ(box, xyz, uvw);
      visu_data_addNodeFromIndex(VISU_DATA(data), atoms->iatype[i], xyz, FALSE);
    }

  /* Add external potentials as nodes. */
  if (atoms->npots)
    {
      VisuNodeValues *vals;
      VisuNodeValuesFrag *fragments;
      VisuNodeValuesFarray *sigmas;
      VisuNodeValuesPole *poles;

      vals = visu_data_getNodeProperties(VISU_DATA(data), _("Fragment"));
      if (vals && VISU_IS_NODE_VALUES_FRAG(vals))
        fragments = VISU_NODE_VALUES_FRAG(vals);
      else
        {
          fragments = visu_node_values_frag_new(VISU_NODE_ARRAY(data),
                                                vals ? _("External potential") : _("Fragment"));
          visu_data_addNodeProperties(VISU_DATA(data), VISU_NODE_VALUES(fragments));
        }
      sigmas = (VisuNodeValuesFarray*)0;
      if (atoms->psigma)
        {
          sigmas = visu_node_values_farray_new(VISU_NODE_ARRAY(data),
                                               _("sigma"), POSINP_SIGMA_SIZE);
          visu_data_addNodeProperties(VISU_DATA(data), VISU_NODE_VALUES(sigmas));
        }
      poles = (VisuNodeValuesPole*)0;
      if (atoms->ppoles)
        {
          poles = visu_node_values_pole_new(VISU_NODE_ARRAY(data), _("poles"));
          visu_data_addNodeProperties(VISU_DATA(data), VISU_NODE_VALUES(poles));
        }
      for (i = 0; i < atoms->npots; i++)
        {
          VisuElement *element;
          VisuNode *node;
          VisuNodeFragment frag;
          gchar *name;
          gboolean created;

          name = g_strdup_printf("%%%s_pot", atoms->potnames[i]);
          element = visu_element_retrieveFromName(name, &created);
          g_free(name);
          if (created)
            {
              VisuElementAtomic *renderer = visu_element_atomic_getFromPool(element);
              VisuElement *eleOrig = visu_element_lookup(atoms->potnames[i]);
              if (atoms->psigma)
                visu_element_atomic_setRadius(renderer, atoms->psigma[i][0]);
              switch (atoms->punits)
                {
                case (POSINP_CELL_UNITS_ANGSTROEM):
                  visu_element_atomic_setUnits(renderer, TOOL_UNITS_ANGSTROEM);
                  break;
                case (POSINP_CELL_UNITS_BOHR):
                  visu_element_atomic_setUnits(renderer, TOOL_UNITS_BOHR);
                  break;
                default:
                  break;
                }
              if (eleOrig)
                {
                  VisuElementRenderer *orig = visu_element_renderer_getFromPool(eleOrig);
                  visu_element_renderer_setColor(VISU_ELEMENT_RENDERER(renderer),
                                                 visu_element_renderer_getColor(orig));
                  visu_element_renderer_setMaterial(VISU_ELEMENT_RENDERER(renderer),
                                                    visu_element_renderer_getMaterial(orig));
                  visu_element_renderer_setMaterialValue(VISU_ELEMENT_RENDERER(renderer),
                                                         .2f, TOOL_MATERIAL_AMB);
                }
            }
          xyz[0] = (float)atoms->pxyz[3 * i + 0];
          xyz[1] = (float)atoms->pxyz[3 * i + 1];
          xyz[2] = (float)atoms->pxyz[3 * i + 2];
          node = visu_data_addNodeFromElement(VISU_DATA(data), element, xyz,
                                              (atoms->punits == POSINP_COORD_UNITS_REDUCED));
          frag.label = g_strdup(_("Pole"));
          frag.id = i;
          visu_node_values_frag_setAt(fragments, node, &frag);
          if (atoms->psigma)
            visu_node_values_farray_setAtDbl(sigmas, node,
                                             atoms->psigma[i], POSINP_SIGMA_SIZE);
          if (atoms->ppoles)
            {
              visu_node_values_pole_setMonoAtDbl(poles, node, atoms->ppoles[i].q0);
              visu_node_values_pole_setDiAtDbl(poles, node, atoms->ppoles[i].q1);
              visu_node_values_pole_setQuadAtDbl(poles, node, atoms->ppoles[i].q2);
            }
        }
    }

  /* We setup comments from ifrztyp. */
  labels = visu_data_getNodeLabels(VISU_DATA(data));
  if (atoms->ifrztyp)
    for (i = 0; i < atoms->nat; i++)
      switch (atoms->ifrztyp[i])
        {
        case POSINP_FROZEN_FULL:
          visu_node_values_string_setAt(labels, visu_node_array_getFromId(VISU_NODE_ARRAY(data), i), "f");
          break;
        case POSINP_FROZEN_Y:
          visu_node_values_string_setAt(labels, visu_node_array_getFromId(VISU_NODE_ARRAY(data), i), "fy");
          break;
        case POSINP_FROZEN_XZ:
          visu_node_values_string_setAt(labels, visu_node_array_getFromId(VISU_NODE_ARRAY(data), i), "fxz");
          break;
        case POSINP_FROZEN_FREE:
        default:
          break;
        }
  /* We setup igspin and igchg as properties. */
  g_value_init(&ig, G_TYPE_INT);
  if (atoms->igspin)
    {
      igspin = visu_node_values_new(VISU_NODE_ARRAY(data),
                                    "IGSpin", G_TYPE_INT, 1);
      for (i = 0; i < atoms->nat; i++)
        {
          g_value_set_int(&ig, atoms->igspin[i]);
          visu_node_values_setAt(igspin, visu_node_array_getFromId(VISU_NODE_ARRAY(data), i), &ig);
        }
      visu_data_addNodeProperties(VISU_DATA(data), igspin);
    }
  if (atoms->igchg)
    {
      igchg = visu_node_values_new(VISU_NODE_ARRAY(data),
                                   "IGChg", G_TYPE_INT, 1);
      for (i = 0; i < atoms->nat; i++)
        {
          g_value_set_int(&ig, atoms->igspin[i]);
          visu_node_values_setAt(igchg, visu_node_array_getFromId(VISU_NODE_ARRAY(data), i), &ig);
        }
      visu_data_addNodeProperties(VISU_DATA(data), igchg);
    }

  /* Add node properties if any. */
  if (atoms->props)
    for (i = 0; i < atoms->nat; i++)
      _setNodeProp(VISU_DATA(data), visu_node_array_getFromId(VISU_NODE_ARRAY(data), i), atoms->props + i);

  /* In free boundary conditions, find the bounding box. */
  if (atoms->BC != POSINP_BC_PERIODIC)
    visu_data_setTightBox(VISU_DATA(data));

  /* We finish with the box description. */
  DBG_fprintf(stderr, "Atomic YAML: apply the box geometry and set the unit.\n");
  switch (atoms->Units)
    {
    case (POSINP_CELL_UNITS_ANGSTROEM):
      visu_box_setUnit(box, TOOL_UNITS_ANGSTROEM);
      break;
    case (POSINP_CELL_UNITS_BOHR):
      visu_box_setUnit(box, TOOL_UNITS_BOHR);
      break;
    default:
      *error = g_error_new(VISU_DATA_LOADABLE_ERROR, DATA_LOADABLE_ERROR_FORMAT,
                           _("Unsupported units.\n"));
      posinp_yaml_free_list(lst);
      return TRUE;
    }

  /* Store the forces, if any. */
  if (atoms->fxyz)
    {
      forces = g_array_sized_new(FALSE, FALSE, sizeof(float), 3 * atoms->nat);
      for (i = 0; i < atoms->nat; i++)
        {
          fxyz[0] = (float)atoms->fxyz[3 * i + 0];
          fxyz[1] = (float)atoms->fxyz[3 * i + 1];
          fxyz[2] = (float)atoms->fxyz[3 * i + 2];
          g_array_append_vals(forces, fxyz, 3);
        }
      visu_node_values_vector_set
        (visu_data_atomic_getForces(VISU_DATA_ATOMIC(data), TRUE), forces);
      g_array_free(forces, TRUE);
    }

  posinp_yaml_free_list(lst);

  return TRUE;
}
#endif
