/* PIKA - Photo and Image Kooker Application
 * a rebranding of The GNU Image Manipulation Program (created with heckimp)
 * A derived work which may be trivial. However, any changes may be (C)2023 by Aldercone Studio
 *
 * Original copyright, applying to most contents (license remains unchanged): 
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * pikaimage-transform.c
 * Copyright (C) 2019 Ell
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gegl.h>

#include "libpikamath/pikamath.h"

#include "core-types.h"

#include "vectors/pikavectors.h"

#include "pika.h"
#include "pika-transform-resize.h"
#include "pika-transform-utils.h"
#include "pikachannel.h"
#include "pikacontext.h"
#include "pikaguide.h"
#include "pikaimage.h"
#include "pikaimage-guides.h"
#include "pikaimage-sample-points.h"
#include "pikaimage-transform.h"
#include "pikaimage-undo.h"
#include "pikaimage-undo-push.h"
#include "pikaitem.h"
#include "pikaobjectqueue.h"
#include "pikaprogress.h"
#include "pikasamplepoint.h"


#define EPSILON 1e-6


/*  local function prototypes  */

static void    pika_image_transform_guides        (PikaImage           *image,
                                                   const PikaMatrix3   *matrix,
                                                   const GeglRectangle *old_bounds);
static void    pika_image_transform_sample_points (PikaImage           *image,
                                                   const PikaMatrix3   *matrix,
                                                   const GeglRectangle *old_bounds);


/*  private functions  */

static void
pika_image_transform_guides (PikaImage           *image,
                             const PikaMatrix3   *matrix,
                             const GeglRectangle *old_bounds)
{
  GList *iter;

  for (iter = pika_image_get_guides (image); iter;)
    {
      PikaGuide           *guide           = iter->data;
      PikaOrientationType  old_orientation = pika_guide_get_orientation (guide);
      gint                 old_position    = pika_guide_get_position (guide);
      PikaOrientationType  new_orientation;
      gint                 new_position;
      PikaVector2          vertices[2];
      gint                 n_vertices;
      PikaVector2          diff;

      iter = g_list_next (iter);

      switch (old_orientation)
        {
        case PIKA_ORIENTATION_HORIZONTAL:
          vertices[0].x = old_bounds->x;
          vertices[0].y = old_bounds->y + old_position;

          vertices[1].x = old_bounds->x + old_bounds->width / 2.0;
          vertices[1].y = old_bounds->y + old_position;
          break;

        case PIKA_ORIENTATION_VERTICAL:
          vertices[0].x = old_bounds->x + old_position;
          vertices[0].y = old_bounds->y;

          vertices[1].x = old_bounds->x + old_position;
          vertices[1].y = old_bounds->y + old_bounds->height / 2.0;
          break;

        case PIKA_ORIENTATION_UNKNOWN:
          g_return_if_reached ();
        }

      pika_transform_polygon (matrix,
                              vertices, 2, FALSE,
                              vertices, &n_vertices);

      if (n_vertices < 2)
        {
          pika_image_remove_guide (image, guide, TRUE);

          continue;
        }

      pika_vector2_sub (&diff, &vertices[1], &vertices[0]);

      if (pika_vector2_length (&diff) <= EPSILON)
        {
          pika_image_remove_guide (image, guide, TRUE);

          continue;
        }

      if (fabs (diff.x) >= fabs (diff.y))
        {
          new_orientation = PIKA_ORIENTATION_HORIZONTAL;
          new_position    = SIGNED_ROUND (vertices[1].y);

          if (new_position < 0 || new_position > pika_image_get_height (image))
            {
              pika_image_remove_guide (image, guide, TRUE);

              continue;
            }
        }
      else
        {
          new_orientation = PIKA_ORIENTATION_VERTICAL;
          new_position    = SIGNED_ROUND (vertices[1].x);

          if (new_position < 0 || new_position > pika_image_get_width (image))
            {
              pika_image_remove_guide (image, guide, TRUE);

              continue;
            }
        }

      if (new_orientation != old_orientation ||
          new_position    != old_position)
        {
          pika_image_undo_push_guide (image, NULL, guide);

          pika_guide_set_orientation (guide, new_orientation);
          pika_guide_set_position    (guide, new_position);

          pika_image_guide_moved (image, guide);
        }
    }
}

static void
pika_image_transform_sample_points (PikaImage           *image,
                                    const PikaMatrix3   *matrix,
                                    const GeglRectangle *old_bounds)
{
  GList *iter;

  for (iter = pika_image_get_sample_points (image); iter;)
    {
      PikaSamplePoint     *sample_point = iter->data;
      gint                 old_x;
      gint                 old_y;
      gint                 new_x;
      gint                 new_y;
      PikaVector2          vertices[1];
      gint                 n_vertices;

      iter = g_list_next (iter);

      pika_sample_point_get_position (sample_point, &old_x, &old_y);

      vertices[0].x = old_x;
      vertices[0].y = old_y;

      pika_transform_polygon (matrix,
                              vertices, 1, FALSE,
                              vertices, &n_vertices);

      if (n_vertices < 1)
        {
          pika_image_remove_sample_point (image, sample_point, TRUE);

          continue;
        }

      new_x = SIGNED_ROUND (vertices[0].x);
      new_y = SIGNED_ROUND (vertices[0].y);

      if (new_x < 0 || new_x >= pika_image_get_width  (image) ||
          new_y < 0 || new_y >= pika_image_get_height (image))
        {
          pika_image_remove_sample_point (image, sample_point, TRUE);

          continue;
        }

      if (new_x != old_x || new_y != old_y)
        pika_image_move_sample_point (image, sample_point, new_x, new_y, TRUE);
    }
}


/*  public functions  */

void
pika_image_transform (PikaImage              *image,
                      PikaContext            *context,
                      const PikaMatrix3      *matrix,
                      PikaTransformDirection  direction,
                      PikaInterpolationType   interpolation_type,
                      PikaTransformResize     clip_result,
                      PikaProgress           *progress)
{
  PikaObjectQueue *queue;
  PikaItem        *item;
  PikaMatrix3      transform;
  GeglRectangle    old_bounds;
  GeglRectangle    new_bounds;

  g_return_if_fail (PIKA_IS_IMAGE (image));
  g_return_if_fail (PIKA_IS_CONTEXT (context));
  g_return_if_fail (matrix != NULL);
  g_return_if_fail (progress == NULL || PIKA_IS_PROGRESS (progress));

  pika_set_busy (image->pika);

  old_bounds.x      = 0;
  old_bounds.y      = 0;
  old_bounds.width  = pika_image_get_width  (image);
  old_bounds.height = pika_image_get_height (image);

  transform = *matrix;

  if (direction == PIKA_TRANSFORM_BACKWARD)
    pika_matrix3_invert (&transform);

  pika_transform_resize_boundary (&transform, clip_result,

                                  old_bounds.x,
                                  old_bounds.y,
                                  old_bounds.x + old_bounds.width,
                                  old_bounds.y + old_bounds.height,

                                  &new_bounds.x,
                                  &new_bounds.y,
                                  &new_bounds.width,
                                  &new_bounds.height);

  new_bounds.width  -= new_bounds.x;
  new_bounds.height -= new_bounds.y;

  pika_matrix3_translate (&transform,
                          old_bounds.x - new_bounds.x,
                          old_bounds.y - new_bounds.y);

  queue    = pika_object_queue_new (progress);
  progress = PIKA_PROGRESS (queue);

  pika_object_queue_push_container (queue, pika_image_get_layers (image));
  pika_object_queue_push (queue, pika_image_get_mask (image));
  pika_object_queue_push_container (queue, pika_image_get_channels (image));
  pika_object_queue_push_container (queue, pika_image_get_vectors (image));

  g_object_freeze_notify (G_OBJECT (image));

  pika_image_undo_group_start (image, PIKA_UNDO_GROUP_IMAGE_TRANSFORM, NULL);

  /*  Transform all layers, channels (including selection mask), and vectors  */
  while ((item = pika_object_queue_pop (queue)))
    {
      PikaTransformResize clip = PIKA_TRANSFORM_RESIZE_ADJUST;

      if (PIKA_IS_CHANNEL (item))
        clip = clip_result;

      pika_item_transform (item,
                           context,
                           &transform, direction,
                           interpolation_type, clip,
                           progress);

      if (PIKA_IS_VECTORS (item))
        pika_item_set_size (item, new_bounds.width, new_bounds.height);
    }

  /*  Resize the image (if needed)  */
  if (! gegl_rectangle_equal (&new_bounds, &old_bounds))
    {
      pika_image_undo_push_image_size (image,
                                       NULL,
                                       new_bounds.x,
                                       new_bounds.y,
                                       new_bounds.width,
                                       new_bounds.height);

      g_object_set (image,
                    "width",  new_bounds.width,
                    "height", new_bounds.height,
                    NULL);
    }

  /*  Transform all Guides  */
  pika_image_transform_guides (image, &transform, &old_bounds);

  /*  Transform all sample points  */
  pika_image_transform_sample_points (image, &transform, &old_bounds);

  pika_image_undo_group_end (image);

  g_object_unref (queue);

  if (! gegl_rectangle_equal (&new_bounds, &old_bounds))
    {
      pika_image_size_changed_detailed (image,
                                        old_bounds.x - new_bounds.x,
                                        old_bounds.y - new_bounds.y,
                                        old_bounds.width,
                                        old_bounds.height);
    }

  g_object_thaw_notify (G_OBJECT (image));

  pika_unset_busy (image->pika);
}
