/* 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 "libpikamath/pikamath.h"

#include "tools-types.h"

#include "config/pikadisplayconfig.h"

#include "core/pika.h"
#include "core/pikabezierdesc.h"
#include "core/pikabrush.h"
#include "core/pikaimage.h"
#include "core/pikatoolinfo.h"

#include "paint/pikabrushcore.h"
#include "paint/pikapaintoptions.h"

#include "display/pikacanvashandle.h"
#include "display/pikacanvaspath.h"
#include "display/pikadisplay.h"
#include "display/pikadisplayshell.h"

#include "pikabrushtool.h"
#include "pikapainttool-paint.h"
#include "pikatoolcontrol.h"


static void   pika_brush_tool_constructed     (GObject           *object);

static void   pika_brush_tool_oper_update     (PikaTool          *tool,
                                               const PikaCoords  *coords,
                                               GdkModifierType    state,
                                               gboolean           proximity,
                                               PikaDisplay       *display);
static void   pika_brush_tool_cursor_update   (PikaTool          *tool,
                                               const PikaCoords  *coords,
                                               GdkModifierType    state,
                                               PikaDisplay       *display);
static void   pika_brush_tool_options_notify  (PikaTool          *tool,
                                               PikaToolOptions   *options,
                                               const GParamSpec  *pspec);

static void   pika_brush_tool_paint_start     (PikaPaintTool     *paint_tool);
static void   pika_brush_tool_paint_end       (PikaPaintTool     *paint_tool);
static void   pika_brush_tool_paint_flush     (PikaPaintTool     *paint_tool);
static PikaCanvasItem *
              pika_brush_tool_get_outline     (PikaPaintTool     *paint_tool,
                                               PikaDisplay       *display,
                                               gdouble            x,
                                               gdouble            y);

static void   pika_brush_tool_brush_changed   (PikaContext       *context,
                                               PikaBrush         *brush,
                                               PikaBrushTool     *brush_tool);
static void   pika_brush_tool_set_brush       (PikaBrushCore     *brush_core,
                                               PikaBrush         *brush,
                                               PikaBrushTool     *brush_tool);

static const PikaBezierDesc *
                 pika_brush_tool_get_boundary (PikaBrushTool     *brush_tool,
                                               gint              *width,
                                               gint              *height);


G_DEFINE_TYPE (PikaBrushTool, pika_brush_tool, PIKA_TYPE_PAINT_TOOL)

#define parent_class pika_brush_tool_parent_class


static void
pika_brush_tool_class_init (PikaBrushToolClass *klass)
{
  GObjectClass       *object_class     = G_OBJECT_CLASS (klass);
  PikaToolClass      *tool_class       = PIKA_TOOL_CLASS (klass);
  PikaPaintToolClass *paint_tool_class = PIKA_PAINT_TOOL_CLASS (klass);

  object_class->constructed     = pika_brush_tool_constructed;

  tool_class->oper_update       = pika_brush_tool_oper_update;
  tool_class->cursor_update     = pika_brush_tool_cursor_update;
  tool_class->options_notify    = pika_brush_tool_options_notify;

  paint_tool_class->paint_start = pika_brush_tool_paint_start;
  paint_tool_class->paint_end   = pika_brush_tool_paint_end;
  paint_tool_class->paint_flush = pika_brush_tool_paint_flush;
  paint_tool_class->get_outline = pika_brush_tool_get_outline;
}

static void
pika_brush_tool_init (PikaBrushTool *brush_tool)
{
  PikaTool *tool = PIKA_TOOL (brush_tool);

  pika_tool_control_set_action_pixel_size (tool->control,
                                           "tools-paintbrush-pixel-size-set");
  pika_tool_control_set_action_size       (tool->control,
                                           "tools-paintbrush-size-set");
  pika_tool_control_set_action_aspect     (tool->control,
                                           "tools-paintbrush-aspect-ratio-set");
  pika_tool_control_set_action_angle      (tool->control,
                                           "tools-paintbrush-angle-set");
  pika_tool_control_set_action_spacing    (tool->control,
                                           "tools-paintbrush-spacing-set");
  pika_tool_control_set_action_hardness   (tool->control,
                                           "tools-paintbrush-hardness-set");
  pika_tool_control_set_action_force      (tool->control,
                                           "tools-paintbrush-force-set");
  pika_tool_control_set_action_object_1   (tool->control,
                                           "context-brush-select-set");
}

static void
pika_brush_tool_constructed (GObject *object)
{
  PikaTool      *tool       = PIKA_TOOL (object);
  PikaPaintTool *paint_tool = PIKA_PAINT_TOOL (object);

  G_OBJECT_CLASS (parent_class)->constructed (object);

  pika_assert (PIKA_IS_BRUSH_CORE (paint_tool->core));

  g_signal_connect_object (pika_tool_get_options (tool), "brush-changed",
                           G_CALLBACK (pika_brush_tool_brush_changed),
                           paint_tool, 0);

  g_signal_connect_object (paint_tool->core, "set-brush",
                           G_CALLBACK (pika_brush_tool_set_brush),
                           paint_tool, 0);
}

static void
pika_brush_tool_oper_update (PikaTool         *tool,
                             const PikaCoords *coords,
                             GdkModifierType   state,
                             gboolean          proximity,
                             PikaDisplay      *display)
{
  PikaPaintOptions *paint_options = PIKA_PAINT_TOOL_GET_OPTIONS (tool);
  PikaImage        *image         = pika_display_get_image (display);

  pika_draw_tool_pause (PIKA_DRAW_TOOL (tool));

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

  if (! pika_color_tool_is_enabled (PIKA_COLOR_TOOL (tool)) &&
      image && proximity)
    {
      PikaContext   *context    = PIKA_CONTEXT (paint_options);
      PikaPaintTool *paint_tool = PIKA_PAINT_TOOL (tool);
      PikaBrushCore *brush_core = PIKA_BRUSH_CORE (paint_tool->core);

      pika_brush_core_set_brush (brush_core,
                                 pika_context_get_brush (context));

      pika_brush_core_set_dynamics (brush_core,
                                    pika_context_get_dynamics (context));

      if (PIKA_BRUSH_CORE_GET_CLASS (brush_core)->handles_transforming_brush)
        {
          pika_brush_core_eval_transform_dynamics (brush_core,
                                                   image,
                                                   paint_options,
                                                   coords);
        }
    }

  pika_draw_tool_resume (PIKA_DRAW_TOOL (tool));
}

static void
pika_brush_tool_cursor_update (PikaTool         *tool,
                               const PikaCoords *coords,
                               GdkModifierType   state,
                               PikaDisplay      *display)
{
  PikaBrushTool *brush_tool = PIKA_BRUSH_TOOL (tool);
  PikaBrushCore *brush_core = PIKA_BRUSH_CORE (PIKA_PAINT_TOOL (brush_tool)->core);

  if (! pika_color_tool_is_enabled (PIKA_COLOR_TOOL (tool)))
    {
      if (! brush_core->main_brush || ! brush_core->dynamics)
        {
          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;
        }
    }

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

static void
pika_brush_tool_options_notify (PikaTool         *tool,
                                PikaToolOptions  *options,
                                const GParamSpec *pspec)
{
  PIKA_TOOL_CLASS (parent_class)->options_notify (tool, options, pspec);

  if (! strcmp (pspec->name, "brush-size")  ||
      ! strcmp (pspec->name, "brush-angle") ||
      ! strcmp (pspec->name, "brush-aspect-ratio"))
    {
      PikaPaintTool *paint_tool = PIKA_PAINT_TOOL (tool);
      PikaBrushCore *brush_core = PIKA_BRUSH_CORE (paint_tool->core);

      g_signal_emit_by_name (brush_core, "set-brush",
                             brush_core->main_brush);
    }
}

static void
pika_brush_tool_paint_start (PikaPaintTool *paint_tool)
{
  PikaBrushTool        *brush_tool = PIKA_BRUSH_TOOL (paint_tool);
  PikaBrushCore        *brush_core = PIKA_BRUSH_CORE (paint_tool->core);
  const PikaBezierDesc *boundary;

  if (PIKA_PAINT_TOOL_CLASS (parent_class)->paint_start)
    PIKA_PAINT_TOOL_CLASS (parent_class)->paint_start (paint_tool);

  boundary = pika_brush_tool_get_boundary (brush_tool,
                                           &brush_tool->boundary_width,
                                           &brush_tool->boundary_height);

  if (boundary)
    brush_tool->boundary = pika_bezier_desc_copy (boundary);

  brush_tool->boundary_scale        = brush_core->scale;
  brush_tool->boundary_aspect_ratio = brush_core->aspect_ratio;
  brush_tool->boundary_angle        = brush_core->angle;
  brush_tool->boundary_reflect      = brush_core->reflect;
  brush_tool->boundary_hardness     = brush_core->hardness;
}

static void
pika_brush_tool_paint_end (PikaPaintTool *paint_tool)
{
  PikaBrushTool *brush_tool = PIKA_BRUSH_TOOL (paint_tool);

  g_clear_pointer (&brush_tool->boundary, pika_bezier_desc_free);

  if (PIKA_PAINT_TOOL_CLASS (parent_class)->paint_end)
    PIKA_PAINT_TOOL_CLASS (parent_class)->paint_end (paint_tool);
}

static void
pika_brush_tool_paint_flush (PikaPaintTool *paint_tool)
{
  PikaBrushTool        *brush_tool = PIKA_BRUSH_TOOL (paint_tool);
  PikaBrushCore        *brush_core = PIKA_BRUSH_CORE (paint_tool->core);
  const PikaBezierDesc *boundary;

  if (PIKA_PAINT_TOOL_CLASS (parent_class)->paint_flush)
    PIKA_PAINT_TOOL_CLASS (parent_class)->paint_flush (paint_tool);

  if (brush_tool->boundary_scale        != brush_core->scale        ||
      brush_tool->boundary_aspect_ratio != brush_core->aspect_ratio ||
      brush_tool->boundary_angle        != brush_core->angle        ||
      brush_tool->boundary_reflect      != brush_core->reflect      ||
      brush_tool->boundary_hardness     != brush_core->hardness)
    {
      g_clear_pointer (&brush_tool->boundary, pika_bezier_desc_free);

      boundary = pika_brush_tool_get_boundary (brush_tool,
                                               &brush_tool->boundary_width,
                                               &brush_tool->boundary_height);

      if (boundary)
        brush_tool->boundary = pika_bezier_desc_copy (boundary);

      brush_tool->boundary_scale        = brush_core->scale;
      brush_tool->boundary_aspect_ratio = brush_core->aspect_ratio;
      brush_tool->boundary_angle        = brush_core->angle;
      brush_tool->boundary_reflect      = brush_core->reflect;
      brush_tool->boundary_hardness     = brush_core->hardness;
    }
}

static PikaCanvasItem *
pika_brush_tool_get_outline (PikaPaintTool *paint_tool,
                             PikaDisplay   *display,
                             gdouble        x,
                             gdouble        y)
{
  PikaBrushTool  *brush_tool = PIKA_BRUSH_TOOL (paint_tool);
  PikaCanvasItem *item;

  item = pika_brush_tool_create_outline (brush_tool, display, x, y);

  if (! item)
    {
      PikaBrushCore *brush_core = PIKA_BRUSH_CORE (paint_tool->core);

      if (brush_core->main_brush && brush_core->dynamics)
        {
          /*  if an outline was expected, but got scaled away by
           *  transform/dynamics, draw a circle in the "normal" size.
           */
          PikaPaintOptions *options;

          options = PIKA_PAINT_TOOL_GET_OPTIONS (brush_tool);

          pika_paint_tool_set_draw_fallback (paint_tool,
                                             TRUE, options->brush_size);
        }
    }

  return item;
}

PikaCanvasItem *
pika_brush_tool_create_outline (PikaBrushTool *brush_tool,
                                PikaDisplay   *display,
                                gdouble        x,
                                gdouble        y)
{
  PikaTool             *tool;
  PikaDisplayShell     *shell;
  const PikaBezierDesc *boundary = NULL;
  gint                  width    = 0;
  gint                  height   = 0;

  g_return_val_if_fail (PIKA_IS_BRUSH_TOOL (brush_tool), NULL);
  g_return_val_if_fail (PIKA_IS_DISPLAY (display), NULL);

  if (pika_paint_tool_paint_is_active (PIKA_PAINT_TOOL (brush_tool)))
    {
      boundary = brush_tool->boundary;
      width    = brush_tool->boundary_width;
      height   = brush_tool->boundary_height;
    }
  else
    {
      boundary = pika_brush_tool_get_boundary (brush_tool, &width, &height);
    }

  if (! boundary)
    return NULL;

  tool  = PIKA_TOOL (brush_tool);
  shell = pika_display_get_shell (display);

  /*  don't draw the boundary if it becomes too small  */
  if (SCALEX (shell, width)  > 4 &&
      SCALEY (shell, height) > 4)
    {
      x -= width  / 2.0;
      y -= height / 2.0;

      if (pika_tool_control_get_precision (tool->control) ==
          PIKA_CURSOR_PRECISION_PIXEL_CENTER)
        {
#define EPSILON 0.000001
          /*  Add EPSILON before rounding since e.g.
           *  (5.0 - 0.5) may end up at (4.499999999....)
           *  due to floating point fnords
           */
          x = RINT (x + EPSILON);
          y = RINT (y + EPSILON);
#undef EPSILON
        }

      return pika_canvas_path_new (shell, boundary, x, y, FALSE,
                                   PIKA_PATH_STYLE_OUTLINE);
    }

  return NULL;
}

static void
pika_brush_tool_brush_changed (PikaContext   *context,
                               PikaBrush     *brush,
                               PikaBrushTool *brush_tool)
{
  PikaPaintTool *paint_tool = PIKA_PAINT_TOOL (brush_tool);
  PikaBrushCore *brush_core = PIKA_BRUSH_CORE (paint_tool->core);

  pika_brush_core_set_brush (brush_core, brush);

}

static void
pika_brush_tool_set_brush (PikaBrushCore *brush_core,
                           PikaBrush     *brush,
                           PikaBrushTool *brush_tool)
{
  pika_draw_tool_pause (PIKA_DRAW_TOOL (brush_tool));

  if (PIKA_BRUSH_CORE_GET_CLASS (brush_core)->handles_transforming_brush)
    {
      PikaPaintCore *paint_core = PIKA_PAINT_CORE (brush_core);

      pika_brush_core_eval_transform_dynamics (brush_core,
                                               NULL,
                                               PIKA_PAINT_TOOL_GET_OPTIONS (brush_tool),
                                               &paint_core->cur_coords);
    }

  pika_draw_tool_resume (PIKA_DRAW_TOOL (brush_tool));
}

static const PikaBezierDesc *
pika_brush_tool_get_boundary (PikaBrushTool *brush_tool,
                              gint          *width,
                              gint          *height)
{
  PikaPaintTool *paint_tool = PIKA_PAINT_TOOL (brush_tool);
  PikaBrushCore *brush_core = PIKA_BRUSH_CORE (paint_tool->core);

  if (paint_tool->draw_brush &&
      brush_core->main_brush &&
      brush_core->dynamics   &&
      brush_core->scale > 0.0)
    {
      return pika_brush_transform_boundary (brush_core->main_brush,
                                            brush_core->scale,
                                            brush_core->aspect_ratio,
                                            brush_core->angle,
                                            brush_core->reflect,
                                            brush_core->hardness,
                                            width,
                                            height);
    }

  return NULL;
}
