/*   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 "rotate.h"
#include <coreTools/toolMatrix.h>

/**
 * SECTION:rotate
 * @short_description: A class defining rotations for a set of nodes.
 *
 * <para>Define and apply a rotation for a set of nodes. The
 * rotation can be changed and the set of nodes also. Each time the
 * rotation is applied, it is added to an undo stack.</para>
 */

/**
 * VisuNodeMoverRotationClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuNodeMoverRotationClass structure.
 *
 * Since: 3.8
 */
/**
 * VisuNodeMoverRotation:
 *
 * An opaque structure.
 *
 * Since: 3.8
 */
struct _Params
{
  gfloat angle;
  gfloat axis[3], center[3];
};
/**
 * VisuNodeMoverRotationPrivate:
 *
 * Private fields for #VisuNodeMoverRotation objects.
 *
 * Since: 3.8
 */
struct _VisuNodeMoverRotationPrivate
{
  struct _Params params;
  struct _Params target;
  gfloat lastAngle;

  GSList *stack;
};


enum
  {
    PROP_0,
    ANGLE_PROP,
    CENTER_PROP,
    AXIS_PROP,
    N_PROP
  };
static GParamSpec *_properties[N_PROP];

static void visu_node_mover_rotation_finalize(GObject *obj);
static void visu_node_mover_rotation_get_property(GObject* obj, guint property_id,
                                                  GValue *value, GParamSpec *pspec);
static void visu_node_mover_rotation_set_property(GObject* obj, guint property_id,
                                                  const GValue *value, GParamSpec *pspec);
static gboolean _validate(const VisuNodeMover *mover);
static void _setup(VisuNodeMover *mover);
static gboolean _apply(VisuNodeMover *mover, VisuNodeArray *arr,
                       const GArray *ids, gfloat completion);
static gboolean _push(VisuNodeMover *mover);
static void _undo(VisuNodeMover *mover, VisuNodeArray *arr, const GArray *ids);

G_DEFINE_TYPE_WITH_CODE(VisuNodeMoverRotation, visu_node_mover_rotation, VISU_TYPE_NODE_MOVER,
                        G_ADD_PRIVATE(VisuNodeMoverRotation))

static void visu_node_mover_rotation_class_init(VisuNodeMoverRotationClass *klass)
{
  DBG_fprintf(stderr, "Visu MoverRotation: creating the class of the object.\n");
  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->finalize = visu_node_mover_rotation_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_node_mover_rotation_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_node_mover_rotation_get_property;
  VISU_NODE_MOVER_CLASS(klass)->validate = _validate;
  VISU_NODE_MOVER_CLASS(klass)->setup = _setup;
  VISU_NODE_MOVER_CLASS(klass)->apply = _apply;
  VISU_NODE_MOVER_CLASS(klass)->push = _push;
  VISU_NODE_MOVER_CLASS(klass)->undo = _undo;

  /**
   * VisuNodeMoverRotation::angle:
   *
   * The angle of rotation.
   *
   * Since: 3.8
   */
  _properties[ANGLE_PROP] = g_param_spec_float("angle", "Angle",
                                               "rotation angle in degrees.",
                                               -G_MAXFLOAT, G_MAXFLOAT, 0.f,
                                               G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  /**
   * VisuNodeMoverRotation::center:
   *
   * The center of rotation.
   *
   * Since: 3.8
   */
  _properties[CENTER_PROP] = g_param_spec_boxed("center", "Center",
                                                "center of rotation.",
                                                TOOL_TYPE_VECTOR,
                                                G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  /**
   * VisuNodeMoverRotation::axis:
   *
   * The axis of rotation.
   *
   * Since: 3.8
   */
  _properties[AXIS_PROP] = g_param_spec_boxed("axis", "Axis",
                                              "axis of rotation.",
                                              TOOL_TYPE_VECTOR,
                                              G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  g_object_class_install_properties(G_OBJECT_CLASS(klass), N_PROP, _properties);
}

static void visu_node_mover_rotation_init(VisuNodeMoverRotation *obj)
{
  DBG_fprintf(stderr, "Visu MoverRotation: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_node_mover_rotation_get_instance_private(obj);

  obj->priv->stack = (GSList*)0;
  obj->priv->params.angle = 0.f;
  obj->priv->params.axis[0] = 0.f;
  obj->priv->params.axis[1] = 0.f;
  obj->priv->params.axis[2] = 1.f;
  obj->priv->params.center[0] = 0.f;
  obj->priv->params.center[1] = 0.f;
  obj->priv->params.center[2] = 0.f;
}
static void visu_node_mover_rotation_get_property(GObject* obj, guint property_id,
                                                  GValue *value, GParamSpec *pspec)
{
  VisuNodeMoverRotation *self = VISU_NODE_MOVER_ROTATION(obj);

  DBG_fprintf(stderr, "Visu MoverRotation: get property %s.\n",
              g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case ANGLE_PROP:
        g_value_set_float(value, self->priv->params.angle);
      break;
    case AXIS_PROP:
      g_value_set_boxed(value, self->priv->params.axis);
      break;
    case CENTER_PROP:
      g_value_set_boxed(value, self->priv->params.center);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_node_mover_rotation_set_property(GObject* obj, guint property_id,
                                                  const GValue *value, GParamSpec *pspec)
{
  VisuNodeMoverRotation *self = VISU_NODE_MOVER_ROTATION(obj);

  DBG_fprintf(stderr, "Visu MoverRotation: set property %s.\n",
              g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case ANGLE_PROP:
        visu_node_mover_rotation_setAngle(self, g_value_get_float(value));
      break;
    case AXIS_PROP:
      visu_node_mover_rotation_setAxis(self, (float*)g_value_get_boxed(value));
      break;
    case CENTER_PROP:
      visu_node_mover_rotation_setCenter(self, (float*)g_value_get_boxed(value));
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_node_mover_rotation_finalize(GObject *obj)
{
  VisuNodeMoverRotation *rot;

  g_return_if_fail(obj);

  DBG_fprintf(stderr, "Visu MoverRotation: finalize object %p.\n", (gpointer)obj);

  rot = VISU_NODE_MOVER_ROTATION(obj);

  /* Free privs elements. */
  if (rot->priv->stack)
    g_slist_free_full(rot->priv->stack, g_free);

  /* Chain up to the parent class */
  DBG_fprintf(stderr, "Visu MoverRotation: chain to parent.\n");
  G_OBJECT_CLASS(visu_node_mover_rotation_parent_class)->finalize(obj);
  DBG_fprintf(stderr, "Visu MoverRotation: freeing ... OK.\n");
}

static gboolean _validate(const VisuNodeMover *mover)
{
  VisuNodeMoverRotation *rot;
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(mover), FALSE);

  rot = VISU_NODE_MOVER_ROTATION(mover);
  if (rot->priv->params.angle == 0.f)
    return FALSE;
  if (rot->priv->params.axis[0] == 0.f &&
      rot->priv->params.axis[1] == 0.f &&
      rot->priv->params.axis[2] == 0.f)
    return FALSE;
  return TRUE;
}
static void _setup(VisuNodeMover *mover)
{
  VisuNodeMoverRotation *rot;
  g_return_if_fail(VISU_IS_NODE_MOVER_ROTATION(mover));

  rot = VISU_NODE_MOVER_ROTATION(mover);
  rot->priv->target = rot->priv->params;
  rot->priv->lastAngle = 0.f;
}
static gboolean _apply(VisuNodeMover *mover, VisuNodeArray *arr,
                       const GArray *ids, gfloat completion)
{
  VisuNodeMoverRotation *rot;
  struct _Params *params;
  
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(mover), FALSE);

  rot = VISU_NODE_MOVER_ROTATION(mover);
  DBG_fprintf(stderr, "Visu MoverRotation: apply rotation %g %gx%gx%g.\n",
              rot->priv->params.angle, rot->priv->params.axis[0],
              rot->priv->params.axis[1], rot->priv->params.axis[2]);
  if (!_validate(mover))
    return FALSE;

  visu_node_array_rotateNodes(arr, ids, rot->priv->target.axis,
                              rot->priv->target.center, rot->priv->target.angle * completion - rot->priv->lastAngle);
  rot->priv->lastAngle = rot->priv->target.angle * completion;
  if (completion == 1.f)
    {
      params = g_malloc(sizeof(struct _Params));
      *params = rot->priv->params;
      rot->priv->stack = g_slist_prepend(rot->priv->stack, params);
    }
  return TRUE;
}
static gboolean _push(VisuNodeMover *mover)
{
  VisuNodeMoverRotation *rot;
  struct _Params *params;
  
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(mover), FALSE);

  rot = VISU_NODE_MOVER_ROTATION(mover);
  if (!_validate(mover))
    return FALSE;
  
  params = g_malloc(sizeof(struct _Params));
  *params = rot->priv->params;
  rot->priv->stack = g_slist_prepend(rot->priv->stack, params);
  return TRUE;
}
static void _undo(VisuNodeMover *mover, VisuNodeArray *arr, const GArray *ids)
{
  VisuNodeMoverRotation *rot;
  struct _Params *params;
  GSList *p;
  
  g_return_if_fail(VISU_IS_NODE_MOVER_ROTATION(mover));

  rot = VISU_NODE_MOVER_ROTATION(mover);
  if (!rot->priv->stack)
    return;
  
  p = rot->priv->stack;
  params = (struct _Params*)p->data;
  visu_node_array_rotateNodes(arr, ids, params->axis, params->center, -params->angle);

  rot->priv->stack = g_slist_next(rot->priv->stack);
  g_free(params);
  g_slist_free_1(p);
}

/**
 * visu_node_mover_rotation_new:
 *
 * Creates a new rotation.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a new #VisuNodeMoverRotation object.
 **/
VisuNodeMoverRotation* visu_node_mover_rotation_new()
{
  return g_object_new(VISU_TYPE_NODE_MOVER_ROTATION, NULL);
}
/**
 * visu_node_mover_rotation_new_full:
 * @ids: (element-type guint): a set of node ids.
 * @axis: (array fixed-size=3): an axis in cartesian coordinates.
 * @center: (array fixed-size=3): a point in cartesian coordinates.
 * @angle: an angle in degrees.
 *
 * Creates a new rotation.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a new #VisuNodeMoverRotation object.
 **/
VisuNodeMoverRotation* visu_node_mover_rotation_new_full(const GArray *ids,
                                                         const gfloat axis[3],
                                                         const gfloat center[3],
                                                         gfloat angle)
{
  return g_object_new(VISU_TYPE_NODE_MOVER_ROTATION, "ids", ids,
                      "axis", axis, "center", center, "angle", angle, NULL);
}

/**
 * visu_node_mover_rotation_setAngle:
 * @rot: a #VisuNodeMoverRotation object.
 * @angle: an angle in degree.
 *
 * Defines the angle of @rot.
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_node_mover_rotation_setAngle(VisuNodeMoverRotation *rot, gfloat angle)
{
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(rot), FALSE);

  if (rot->priv->params.angle == angle)
    return FALSE;

  rot->priv->params.angle = angle;
  g_object_notify_by_pspec(G_OBJECT(rot), _properties[ANGLE_PROP]);
  g_object_notify(G_OBJECT(rot), "valid");
  return TRUE;
}
/**
 * visu_node_mover_rotation_setCenter:
 * @rot: a #VisuNodeMoverRotation object.
 * @center: (array fixed-size=3): a point in cartesian coordinates.
 *
 * Defines the center of @rot.
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_node_mover_rotation_setCenter(VisuNodeMoverRotation *rot,
                                            const gfloat center[3])
{
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(rot), FALSE);

  DBG_fprintf(stderr, "Visu MoverRotation: set center %gx%gx%g.\n",
              center[0], center[1], center[2]);
  if (!tool_vector_set(rot->priv->params.center, center))
    return FALSE;

  g_object_notify_by_pspec(G_OBJECT(rot), _properties[CENTER_PROP]);
  g_object_notify(G_OBJECT(rot), "valid");
  return TRUE;
}
/**
 * visu_node_mover_rotation_setAxis:
 * @rot: a #VisuNodeMoverRotation object.
 * @axis: (array fixed-size=3): an axis in cartesian coordinates.
 *
 * Defines the axis of @rot.
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_node_mover_rotation_setAxis(VisuNodeMoverRotation *rot,
                                          const gfloat axis[3])
{
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(rot), FALSE);

  DBG_fprintf(stderr, "Visu MoverRotation: set center %gx%gx%g.\n",
              axis[0], axis[1], axis[2]);
  if (!tool_vector_set(rot->priv->params.axis, axis))
    return FALSE;

  g_object_notify_by_pspec(G_OBJECT(rot), _properties[AXIS_PROP]);
  g_object_notify(G_OBJECT(rot), "valid");
  return TRUE;
}

/**
 * visu_node_mover_rotation_getAngle:
 * @rot: a #VisuNodeMoverRotation object.
 *
 * Retrieves the rotation angle.
 *
 * Since: 3.8
 *
 * Returns: an angle in degrees.
 **/
gfloat visu_node_mover_rotation_getAngle(const VisuNodeMoverRotation *rot)
{
  g_return_val_if_fail(VISU_IS_NODE_MOVER_ROTATION(rot), 0.f);

  return rot->priv->params.angle;
}
/**
 * visu_node_mover_rotation_getCenter:
 * @rot: a #VisuNodeMoverRotation object.
 * @center: (out) (array fixed-size=3): a location for the center.
 *
 * Retrieves the rotation center.
 *
 * Since: 3.8
 **/
void visu_node_mover_rotation_getCenter(const VisuNodeMoverRotation *rot,
                                        gfloat center[3])
{
  g_return_if_fail(VISU_IS_NODE_MOVER_ROTATION(rot));

  tool_vector_set(center, rot->priv->params.center);
}
/**
 * visu_node_mover_rotation_getAxis:
 * @rot: a #VisuNodeMoverRotation object.
 * @axis: (out) (array fixed-size=3): a location for the axis.
 *
 * Retrieves the rotation axis.
 *
 * Since: 3.8
 **/
void visu_node_mover_rotation_getAxis(const VisuNodeMoverRotation *rot,
                                      gfloat axis[3])
{
  g_return_if_fail(VISU_IS_NODE_MOVER_ROTATION(rot));

  tool_vector_set(axis, rot->priv->params.axis);
}

