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

	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 "dumpToYaml.h"

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

#include <visu_tools.h>
#include <visu_dataloadable.h>
#include <extraFunctions/geometry.h>

static VisuDumpData *yaml = NULL;

/**
 * SECTION:dumpToYaml
 * @short_description: add an export capability of current positions.
 *
 * This provides a write routine to export V_Sim current
 * coordinates. It has several options to output or not hiddden nodes
 * or replicated nodes.
 */

static gboolean writeDataInYaml(VisuDumpData *format, const char* filename,
				 VisuData *dataObj, GError **error);

const VisuDumpData* visu_dump_yaml_getStatic()
{
  const gchar *typeYAML[] = {"*.yaml", (char*)0};
#define descrYAML _("YAML file (current positions)")

  if (yaml)
    return yaml;

  yaml = visu_dump_data_new(descrYAML, typeYAML, writeDataInYaml);
  
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(yaml), "delete_hidden_nodes",
				_("Don't output hidden nodes"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(yaml), "comment_hidden_nodes",
				_("Comment hidden nodes (if output)"), TRUE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(yaml), "expand_box",
				_("Keep primitive box (in case of node expansion)"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(yaml), "reduced_coordinates",
				_("Export positions in reduced coordinates"), FALSE);
  tool_file_format_addPropertyBoolean(TOOL_FILE_FORMAT(yaml), "type_alignment",
				_("Export nodes sorted by elements"), FALSE);

  return yaml;
}

static gboolean writeDataInYaml(VisuDumpData *format, const char* filename,
				 VisuData *dataObj, GError **error)
{
  const gchar *nom;
  gchar *prevFile;
  char tmpChr;
  gboolean suppr, comment, expand, reduced, eleSort;
  float factor, xyz[3], ext[3], uvw[3], vertices[8][3], box[6];
  double ene;
  VisuNodeArrayIter iter;
  GString *output;
  const gchar *nodeComment;
  ToolFileFormatIter it;
  VisuBox *boxObj;

  g_return_val_if_fail(error && !*error, FALSE);

  comment = TRUE;
  expand  = FALSE;
  suppr   = FALSE;
  reduced = FALSE;
  eleSort = FALSE;
  it.lst = (GList*)0;
  for (tool_file_format_iterNextProperty(TOOL_FILE_FORMAT(format), &it); it.lst;
       tool_file_format_iterNextProperty(TOOL_FILE_FORMAT(format), &it))
    {
      DBG_fprintf(stderr, "Dump YAML: test property '%s'.\n", it.name);
      if (strcmp(it.name, "comment_hidden_nodes") == 0)
	comment = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "expand_box") == 0)
	expand  = !g_value_get_boolean(it.val);
      else if (strcmp(it.name, "delete_hidden_nodes") == 0)
	suppr   = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "reduced_coordinates") == 0)
	reduced = g_value_get_boolean(it.val);
      else if (strcmp(it.name, "type_alignment") == 0)
	eleSort = g_value_get_boolean(it.val);
    }

  DBG_fprintf(stderr, "Dump YAML: begin export of current positions...\n");
  DBG_fprintf(stderr, " | comment %d ;\n", comment);
  DBG_fprintf(stderr, " | expand  %d ;\n", expand);
  DBG_fprintf(stderr, " | suppr   %d ;\n", suppr);
  DBG_fprintf(stderr, " | reduced %d ;\n", reduced);
  DBG_fprintf(stderr, " | eleSort %d ;\n", eleSort);

  output = g_string_new("---\n");

  boxObj = visu_boxed_getBox(VISU_BOXED(dataObj));
  visu_box_getVertices(boxObj, vertices, expand);
  box[0] = vertices[1][0] - vertices[0][0];
  box[1] = vertices[3][0] - vertices[0][0];
  box[2] = vertices[3][1] - vertices[0][1];
  box[3] = vertices[4][0] - vertices[0][0];
  box[4] = vertices[4][1] - vertices[0][1];
  box[5] = vertices[4][2] - vertices[0][2];
  if (ABS(box[1]) > 1e-8 || ABS(box[3]) > 1e-8 || ABS(box[4]) > 1e-8)
    {
      g_set_error_literal(error, VISU_DUMP_ERROR, DUMP_ERROR_ENCODE,
                          "YAML format supports only orthorhombic cell.");
      return FALSE;
    }

  if (reduced)
    g_string_append(output, "  units: reduced\n");
  else if (visu_box_getUnit(boxObj) == TOOL_UNITS_ANGSTROEM)
    g_string_append(output, "  units: angstroem\n");
  
  
  switch (visu_box_getBoundary(boxObj))
    {
    case VISU_BOX_PERIODIC:
      if (reduced && visu_box_getUnit(boxObj) != TOOL_UNITS_BOHR)
        {
          factor = tool_physic_getUnitConversionFactor(visu_box_getUnit(boxObj),
                                                       TOOL_UNITS_BOHR);
          g_string_append_printf(output, "  cell: [%17.8g, %17.8g, %17.8g]\n",
                                 box[0] * factor, box[2] * factor, box[5] * factor);
        }
      else
        g_string_append_printf(output, "  cell: [%17.8g, %17.8g, %17.8g]\n",
                               box[0], box[2], box[5]);
      break;
    case VISU_BOX_SURFACE_ZX:
      if (reduced && visu_box_getUnit(boxObj) != TOOL_UNITS_BOHR)
        {
          factor = tool_physic_getUnitConversionFactor(visu_box_getUnit(boxObj),
                                                       TOOL_UNITS_BOHR);
          g_string_append_printf(output, "  cell: [%17.8g, .inf, %17.8g]\n",
                                 box[0] * factor, box[5] * factor);
        }
      else
        g_string_append_printf(output, "  cell: [%17.8g, .inf, %17.8g]\n",
                               box[0], box[5]);
      break;
    case VISU_BOX_FREE:
      break;
    default:
      g_set_error_literal(error, VISU_DUMP_ERROR, DUMP_ERROR_ENCODE,
                          "YAML format does not support the given periodicity.");
      return FALSE;
    }

  visu_box_getVertices(boxObj, vertices, FALSE);
  if (expand)
    visu_box_getExtension(boxObj, ext);
  else
    {
      ext[0] = 0.;
      ext[1] = 0.;
      ext[2] = 0.;
    }

  g_string_append(output, "  positions:\n");
  visu_node_array_iter_new(VISU_NODE_ARRAY(dataObj), &iter);
  for ((eleSort)?visu_node_array_iterStart(VISU_NODE_ARRAY(dataObj), &iter):
	 visu_node_array_iterStartNumber(VISU_NODE_ARRAY(dataObj), &iter);
       iter.node && iter.element;
       (eleSort)?visu_node_array_iterNext(VISU_NODE_ARRAY(dataObj), &iter):
	 visu_node_array_iterNextNodeNumber(VISU_NODE_ARRAY(dataObj), &iter))
    {
      if ((visu_element_getRendered(iter.element) && iter.node->rendered) || !comment)
	tmpChr = '-';
      else
	tmpChr = '#';

      visu_data_getNodePosition(dataObj, iter.node, xyz);

      if ((visu_element_getRendered(iter.element) && iter.node->rendered) || !suppr)
	{
	  xyz[0] += ext[0] * vertices[1][0] + ext[1] * vertices[3][0] +
	    ext[2] * vertices[4][0];
	  xyz[1] += ext[1] * vertices[3][1] + ext[2] * vertices[4][1];
	  xyz[2] += ext[2] * vertices[4][2];
	  
	  if (reduced)
	    {
	      visu_box_convertXYZtoBoxCoordinates(boxObj, uvw, xyz);
	      uvw[0] /= (1.f + 2.f * ext[0]);
	      uvw[1] /= (1.f + 2.f * ext[1]);
	      uvw[2] /= (1.f + 2.f * ext[2]);
	    }
	  else
	    {
	      uvw[0] = xyz[0];
	      uvw[1] = xyz[1];
	      uvw[2] = xyz[2];
	    }
	  nodeComment = visu_data_getNodeLabelAt(dataObj, iter.node);
          if (nodeComment)
            g_string_append_printf(output, "  %c {%s: [%17.8g, %17.8g, %17.8g], label: %s}\n",
                                   tmpChr, visu_element_getName(iter.element),
                                   uvw[0], uvw[1], uvw[2], nodeComment);
          else
            g_string_append_printf(output, "  %c %s: [%17.8g, %17.8g, %17.8g]\n",
                                   tmpChr, visu_element_getName(iter.element),
                                   uvw[0], uvw[1], uvw[2]);
	}
    }

  g_string_append(output, "  properties:\n");
  g_string_append(output, "    info: exported from V_Sim\n");
  if (VISU_IS_DATA_LOADABLE(dataObj))
    {
      nom = visu_data_loadable_getFilename(VISU_DATA_LOADABLE(dataObj), 0);
      prevFile = g_path_get_basename(nom);
      g_string_append_printf(output, "    source: %s\n", prevFile);
      g_free(prevFile);
    }
  g_object_get(G_OBJECT(dataObj), "totalEnergy", &ene, NULL);
  if (ene != G_MAXFLOAT)
    g_string_append_printf(output, "    totalEnergy (eV): %22.16f\n", ene);
      
  g_file_set_contents(filename, output->str, -1, error);
  g_string_free(output, TRUE);

  if (*error)
    return FALSE;
  else
    return TRUE;
}
