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

#include <gegl.h>
#include <gtk/gtk.h>

#include "libpikawidgets/pikawidgets.h"

#include "tools-types.h"

#include "config/pikadisplayconfig.h"

#include "core/pikadrawable-transform.h"
#include "core/pikaguide.h"
#include "core/pikaimage.h"
#include "core/pikaimage-flip.h"
#include "core/pikaimage-item-list.h"
#include "core/pikaimage-pick-item.h"
#include "core/pikalayer.h"
#include "core/pikalayermask.h"
#include "core/pikapickable.h"
#include "core/pikaprogress.h"

#include "widgets/pikahelp-ids.h"
#include "widgets/pikawidgets-utils.h"

#include "display/pikacanvasitem.h"
#include "display/pikadisplay.h"
#include "display/pikadisplayshell.h"
#include "display/pikadisplayshell-appearance.h"

#include "pikaflipoptions.h"
#include "pikafliptool.h"
#include "pikatoolcontrol.h"

#include "pika-intl.h"


/*  local function prototypes  */

static void         pika_flip_tool_button_press  (PikaTool             *tool,
                                                  const PikaCoords     *coords,
                                                  guint32               time,
                                                  GdkModifierType       state,
                                                  PikaButtonPressType   press_type,
                                                  PikaDisplay          *display);
static void         pika_flip_tool_modifier_key  (PikaTool             *tool,
                                                  GdkModifierType       key,
                                                  gboolean              press,
                                                  GdkModifierType       state,
                                                  PikaDisplay          *display);
static void         pika_flip_tool_oper_update   (PikaTool             *tool,
                                                  const PikaCoords     *coords,
                                                  GdkModifierType       state,
                                                  gboolean              proximity,
                                                  PikaDisplay          *display);
static void         pika_flip_tool_cursor_update (PikaTool             *tool,
                                                  const PikaCoords     *coords,
                                                  GdkModifierType       state,
                                                  PikaDisplay          *display);

static void         pika_flip_tool_draw          (PikaDrawTool         *draw_tool);

static gchar      * pika_flip_tool_get_undo_desc (PikaTransformTool    *tr_tool);
static GeglBuffer * pika_flip_tool_transform     (PikaTransformTool    *tr_tool,
                                                  GList                *objects,
                                                  GeglBuffer           *orig_buffer,
                                                  gint                  orig_offset_x,
                                                  gint                  orig_offset_y,
                                                  PikaColorProfile    **buffer_profile,
                                                  gint                 *new_offset_x,
                                                  gint                 *new_offset_y);

static PikaOrientationType   pika_flip_tool_get_flip_type  (PikaFlipTool      *flip);


G_DEFINE_TYPE (PikaFlipTool, pika_flip_tool, PIKA_TYPE_TRANSFORM_TOOL)

#define parent_class pika_flip_tool_parent_class


void
pika_flip_tool_register (PikaToolRegisterCallback  callback,
                         gpointer                  data)
{
  (* callback) (PIKA_TYPE_FLIP_TOOL,
                PIKA_TYPE_FLIP_OPTIONS,
                pika_flip_options_gui,
                PIKA_CONTEXT_PROP_MASK_BACKGROUND,
                "pika-flip-tool",
                _("Flip"),
                _("Flip Tool: "
                  "Reverse the layer, selection or path horizontally or vertically"),
                N_("_Flip"), "<shift>F",
                NULL, PIKA_HELP_TOOL_FLIP,
                PIKA_ICON_TOOL_FLIP,
                data);
}

static void
pika_flip_tool_class_init (PikaFlipToolClass *klass)
{
  PikaToolClass          *tool_class      = PIKA_TOOL_CLASS (klass);
  PikaDrawToolClass      *draw_tool_class = PIKA_DRAW_TOOL_CLASS (klass);
  PikaTransformToolClass *tr_class        = PIKA_TRANSFORM_TOOL_CLASS (klass);

  tool_class->button_press  = pika_flip_tool_button_press;
  tool_class->modifier_key  = pika_flip_tool_modifier_key;
  tool_class->oper_update   = pika_flip_tool_oper_update;
  tool_class->cursor_update = pika_flip_tool_cursor_update;

  draw_tool_class->draw     = pika_flip_tool_draw;

  tr_class->get_undo_desc   = pika_flip_tool_get_undo_desc;
  tr_class->transform       = pika_flip_tool_transform;

  tr_class->undo_desc       = C_("undo-type", "Flip");
  tr_class->progress_text   = _("Flipping");
}

static void
pika_flip_tool_init (PikaFlipTool *flip_tool)
{
  PikaTool *tool = PIKA_TOOL (flip_tool);

  pika_tool_control_set_snap_to            (tool->control, FALSE);
  pika_tool_control_set_precision          (tool->control,
                                            PIKA_CURSOR_PRECISION_PIXEL_CENTER);
  pika_tool_control_set_cursor             (tool->control, PIKA_CURSOR_MOUSE);
  pika_tool_control_set_toggle_cursor      (tool->control, PIKA_CURSOR_MOUSE);
  pika_tool_control_set_tool_cursor        (tool->control,
                                            PIKA_TOOL_CURSOR_FLIP_HORIZONTAL);
  pika_tool_control_set_toggle_tool_cursor (tool->control,
                                            PIKA_TOOL_CURSOR_FLIP_VERTICAL);

  flip_tool->guide = NULL;
}

static void
pika_flip_tool_button_press (PikaTool            *tool,
                             const PikaCoords    *coords,
                             guint32              time,
                             GdkModifierType      state,
                             PikaButtonPressType  press_type,
                             PikaDisplay         *display)
{
  PikaTransformTool *tr_tool = PIKA_TRANSFORM_TOOL (tool);

  tool->display = display;

  pika_transform_tool_transform (tr_tool, display);

  pika_tool_control (tool, PIKA_TOOL_ACTION_HALT, display);
}

static void
pika_flip_tool_modifier_key (PikaTool        *tool,
                             GdkModifierType  key,
                             gboolean         press,
                             GdkModifierType  state,
                             PikaDisplay     *display)
{
  PikaFlipOptions *options = PIKA_FLIP_TOOL_GET_OPTIONS (tool);

  if (key == pika_get_toggle_behavior_mask ())
    {
      switch (options->flip_type)
        {
        case PIKA_ORIENTATION_HORIZONTAL:
          g_object_set (options,
                        "flip-type", PIKA_ORIENTATION_VERTICAL,
                        NULL);
          break;

        case PIKA_ORIENTATION_VERTICAL:
          g_object_set (options,
                        "flip-type", PIKA_ORIENTATION_HORIZONTAL,
                        NULL);
          break;

        default:
          break;
        }
    }
}

static void
pika_flip_tool_oper_update (PikaTool         *tool,
                            const PikaCoords *coords,
                            GdkModifierType   state,
                            gboolean          proximity,
                            PikaDisplay      *display)
{
  PikaFlipTool     *flip      = PIKA_FLIP_TOOL (tool);
  PikaDrawTool     *draw_tool = PIKA_DRAW_TOOL (tool);
  PikaFlipOptions  *options   = PIKA_FLIP_TOOL_GET_OPTIONS (tool);
  PikaDisplayShell *shell     = pika_display_get_shell (display);
  PikaImage        *image     = pika_display_get_image (display);
  PikaGuide        *guide     = NULL;

  if (pika_display_shell_get_show_guides (shell) &&
      proximity)
    {
      gint snap_distance = display->config->snap_distance;

      guide = pika_image_pick_guide (image, coords->x, coords->y,
                                     FUNSCALEX (shell, snap_distance),
                                     FUNSCALEY (shell, snap_distance));
    }

  if (flip->guide != guide ||
      (guide && ! pika_draw_tool_is_active (draw_tool)))
    {
      pika_draw_tool_pause (draw_tool);

      if (pika_draw_tool_is_active (draw_tool) &&
          draw_tool->display != display)
        pika_draw_tool_stop (draw_tool);

      flip->guide = guide;

      if (! pika_draw_tool_is_active (draw_tool))
        pika_draw_tool_start (draw_tool, display);

      pika_draw_tool_resume (draw_tool);
    }

  gtk_widget_set_sensitive (options->direction_frame, guide == NULL);

  PIKA_TOOL_CLASS (parent_class)->oper_update (tool,
                                               coords, state, proximity,
                                               display);
}

static void
pika_flip_tool_cursor_update (PikaTool         *tool,
                              const PikaCoords *coords,
                              GdkModifierType   state,
                              PikaDisplay      *display)
{
  PikaTransformTool *tr_tool = PIKA_TRANSFORM_TOOL (tool);
  PikaFlipTool      *flip    = PIKA_FLIP_TOOL (tool);
  GList             *selected_objects;

  selected_objects = pika_transform_tool_check_selected_objects (tr_tool, display, NULL);

  if (! selected_objects)
    {
      pika_tool_set_cursor (tool, display,
                            pika_tool_control_get_cursor (tool->control),
                            pika_tool_control_get_tool_cursor (tool->control),
                            PIKA_CURSOR_MODIFIER_BAD);
      return;
    }
  g_list_free (selected_objects);

  pika_tool_control_set_toggled (tool->control,
                                 pika_flip_tool_get_flip_type (flip) ==
                                 PIKA_ORIENTATION_VERTICAL);

  PIKA_TOOL_CLASS (parent_class)->cursor_update (tool, coords, state, display);
}

static void
pika_flip_tool_draw (PikaDrawTool *draw_tool)
{
  PikaFlipTool *flip = PIKA_FLIP_TOOL (draw_tool);

  if (flip->guide)
    {
      PikaCanvasItem *item;
      PikaGuideStyle  style;

      style = pika_guide_get_style (flip->guide);

      item = pika_draw_tool_add_guide (draw_tool,
                                       pika_guide_get_orientation (flip->guide),
                                       pika_guide_get_position (flip->guide),
                                       style);
      pika_canvas_item_set_highlight (item, TRUE);
    }
}

static gchar *
pika_flip_tool_get_undo_desc (PikaTransformTool *tr_tool)
{
  PikaFlipTool *flip = PIKA_FLIP_TOOL (tr_tool);

  switch (pika_flip_tool_get_flip_type (flip))
    {
    case PIKA_ORIENTATION_HORIZONTAL:
      return g_strdup (C_("undo-type", "Flip horizontally"));

    case PIKA_ORIENTATION_VERTICAL:
      return g_strdup (C_("undo-type", "Flip vertically"));

    default:
      /* probably this is not actually reached today, but
       * could be if someone defined FLIP_DIAGONAL, say...
       */
      return PIKA_TRANSFORM_TOOL_CLASS (parent_class)->get_undo_desc (tr_tool);
    }
}

static GeglBuffer *
pika_flip_tool_transform (PikaTransformTool *tr_tool,
                          GList             *objects,
                          GeglBuffer        *orig_buffer,
                          gint               orig_offset_x,
                          gint               orig_offset_y,
                          PikaColorProfile **buffer_profile,
                          gint              *new_offset_x,
                          gint              *new_offset_y)
{
  PikaFlipTool         *flip        = PIKA_FLIP_TOOL (tr_tool);
  PikaFlipOptions      *options     = PIKA_FLIP_TOOL_GET_OPTIONS (tr_tool);
  PikaTransformOptions *tr_options  = PIKA_TRANSFORM_TOOL_GET_OPTIONS (tr_tool);
  PikaContext          *context     = PIKA_CONTEXT (options);
  PikaOrientationType   flip_type   = PIKA_ORIENTATION_UNKNOWN;
  gdouble               axis        = 0.0;
  gboolean              clip_result = FALSE;
  GeglBuffer           *ret         = NULL;

  flip_type = pika_flip_tool_get_flip_type (flip);

  if (flip->guide)
    {
      axis = pika_guide_get_position (flip->guide);
    }
  else
    {
      switch (flip_type)
        {
        case PIKA_ORIENTATION_HORIZONTAL:
          axis = ((gdouble) tr_tool->x1 +
                  (gdouble) (tr_tool->x2 - tr_tool->x1) / 2.0);
          break;

        case PIKA_ORIENTATION_VERTICAL:
          axis = ((gdouble) tr_tool->y1 +
                  (gdouble) (tr_tool->y2 - tr_tool->y1) / 2.0);
          break;

        default:
          break;
        }
    }

  switch (tr_options->clip)
    {
    case PIKA_TRANSFORM_RESIZE_ADJUST:
      clip_result = FALSE;
      break;

    case PIKA_TRANSFORM_RESIZE_CLIP:
      clip_result = TRUE;
      break;

    default:
      g_return_val_if_reached (NULL);
    }

  if (orig_buffer)
    {
      /*  this happens when transforming a selection cut out of a
       *  normal drawable
       */

      g_return_val_if_fail (PIKA_IS_DRAWABLE (objects->data), NULL);

      ret = pika_drawable_transform_buffer_flip (PIKA_DRAWABLE (objects->data),
                                                 context,
                                                 orig_buffer,
                                                 orig_offset_x,
                                                 orig_offset_y,
                                                 flip_type, axis,
                                                 clip_result,
                                                 buffer_profile,
                                                 new_offset_x,
                                                 new_offset_y);
    }
  else if (g_list_length (objects) == 1 && PIKA_IS_IMAGE (objects->data))
    {
      /*  this happens for images  */
      PikaTransformToolClass *tr_class = PIKA_TRANSFORM_TOOL_GET_CLASS (tr_tool);
      PikaProgress           *progress;

      progress = pika_progress_start (PIKA_PROGRESS (tr_tool), FALSE,
                                      "%s", tr_class->progress_text);

      pika_image_flip_full (PIKA_IMAGE (objects->data), context,
                            flip_type, axis, clip_result,
                            progress);

      if (progress)
        pika_progress_end (progress);
    }
  else
    {
      /*  this happens for entire drawables, paths and layer groups  */
      pika_image_item_list_flip (pika_item_get_image (objects->data),
                                 objects, context,
                                 flip_type, axis, clip_result);
    }

  return ret;
}

static PikaOrientationType
pika_flip_tool_get_flip_type (PikaFlipTool *flip)
{
  PikaFlipOptions *options = PIKA_FLIP_TOOL_GET_OPTIONS (flip);

  if (flip->guide)
    {
      switch (pika_guide_get_orientation (flip->guide))
        {
        case PIKA_ORIENTATION_HORIZONTAL:
          return PIKA_ORIENTATION_VERTICAL;

        case PIKA_ORIENTATION_VERTICAL:
          return PIKA_ORIENTATION_HORIZONTAL;

        default:
          return pika_guide_get_orientation (flip->guide);
        }
    }
  else
    {
      return options->flip_type;
    }
}
