/* 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 <cairo.h>
#include <gegl.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

#include "libpikabase/pikabase.h"
#include "libpikacolor/pikacolor.h"

#include "core-types.h"

#include "pika-memsize.h"
#include "pikaimage.h"
#include "pikaimage-undo-push.h"
#include "pikapalette.h"
#include "pikapalette-load.h"
#include "pikapalette-save.h"
#include "pikatagged.h"
#include "pikatempbuf.h"

#include "pika-intl.h"


#define RGB_EPSILON 1e-6

enum
{
  ENTRY_CHANGED,
  LAST_SIGNAL
};


/*  local function prototypes  */

static void          pika_palette_tagged_iface_init (PikaTaggedInterface  *iface);

static void          pika_palette_finalize          (GObject              *object);

static gint64        pika_palette_get_memsize       (PikaObject           *object,
                                                     gint64               *gui_size);

static void          pika_palette_get_preview_size  (PikaViewable         *viewable,
                                                     gint                  size,
                                                     gboolean              popup,
                                                     gboolean              dot_for_dot,
                                                     gint                 *width,
                                                     gint                 *height);
static gboolean      pika_palette_get_popup_size    (PikaViewable         *viewable,
                                                     gint                  width,
                                                     gint                  height,
                                                     gboolean              dot_for_dot,
                                                     gint                 *popup_width,
                                                     gint                 *popup_height);
static PikaTempBuf * pika_palette_get_new_preview   (PikaViewable         *viewable,
                                                     PikaContext          *context,
                                                     gint                  width,
                                                     gint                  height);
static gchar       * pika_palette_get_description   (PikaViewable         *viewable,
                                                     gchar               **tooltip);
static const gchar * pika_palette_get_extension     (PikaData             *data);
static void          pika_palette_copy              (PikaData             *data,
                                                     PikaData             *src_data);
static void          pika_palette_real_entry_changed (PikaPalette         *palette,
                                                      gint                 index);

static void          pika_palette_entry_free        (PikaPaletteEntry     *entry);
static gint64        pika_palette_entry_get_memsize (PikaPaletteEntry     *entry,
                                                     gint64               *gui_size);
static gchar       * pika_palette_get_checksum      (PikaTagged           *tagged);


G_DEFINE_TYPE_WITH_CODE (PikaPalette, pika_palette, PIKA_TYPE_DATA,
                         G_IMPLEMENT_INTERFACE (PIKA_TYPE_TAGGED,
                                                pika_palette_tagged_iface_init))

#define parent_class pika_palette_parent_class

static guint signals[LAST_SIGNAL] = { 0 };

static void
pika_palette_class_init (PikaPaletteClass *klass)
{
  GObjectClass      *object_class      = G_OBJECT_CLASS (klass);
  PikaObjectClass   *pika_object_class = PIKA_OBJECT_CLASS (klass);
  PikaViewableClass *viewable_class    = PIKA_VIEWABLE_CLASS (klass);
  PikaDataClass     *data_class        = PIKA_DATA_CLASS (klass);

  signals[ENTRY_CHANGED] = g_signal_new ("entry-changed",
                                         G_TYPE_FROM_CLASS (klass),
                                         G_SIGNAL_RUN_FIRST,
                                         G_STRUCT_OFFSET (PikaPaletteClass, entry_changed),
                                         NULL, NULL, NULL,
                                         G_TYPE_NONE, 1,
                                         G_TYPE_INT);

  object_class->finalize            = pika_palette_finalize;

  pika_object_class->get_memsize    = pika_palette_get_memsize;

  viewable_class->default_icon_name = "gtk-select-color";
  viewable_class->get_preview_size  = pika_palette_get_preview_size;
  viewable_class->get_popup_size    = pika_palette_get_popup_size;
  viewable_class->get_new_preview   = pika_palette_get_new_preview;
  viewable_class->get_description   = pika_palette_get_description;

  data_class->save                  = pika_palette_save;
  data_class->get_extension         = pika_palette_get_extension;
  data_class->copy                  = pika_palette_copy;

  klass->entry_changed              = pika_palette_real_entry_changed;
}

static void
pika_palette_tagged_iface_init (PikaTaggedInterface *iface)
{
  iface->get_checksum = pika_palette_get_checksum;
}

static void
pika_palette_init (PikaPalette *palette)
{
  palette->colors    = NULL;
  palette->n_colors  = 0;
  palette->n_columns = 0;
}

static void
pika_palette_finalize (GObject *object)
{
  PikaPalette *palette = PIKA_PALETTE (object);

  if (palette->colors)
    {
      g_list_free_full (palette->colors,
                        (GDestroyNotify) pika_palette_entry_free);
      palette->colors = NULL;
    }

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static gint64
pika_palette_get_memsize (PikaObject *object,
                          gint64     *gui_size)
{
  PikaPalette *palette = PIKA_PALETTE (object);
  gint64       memsize = 0;

  memsize += pika_g_list_get_memsize_foreach (palette->colors,
                                              (PikaMemsizeFunc)
                                              pika_palette_entry_get_memsize,
                                              gui_size);

  return memsize + PIKA_OBJECT_CLASS (parent_class)->get_memsize (object,
                                                                  gui_size);
}

static void
pika_palette_get_preview_size (PikaViewable *viewable,
                               gint          size,
                               gboolean      popup,
                               gboolean      dot_for_dot,
                               gint         *width,
                               gint         *height)
{
  *width  = size;
  *height = 1 + size / 2;
}

static gboolean
pika_palette_get_popup_size (PikaViewable *viewable,
                             gint          width,
                             gint          height,
                             gboolean      dot_for_dot,
                             gint         *popup_width,
                             gint         *popup_height)
{
  PikaPalette *palette = PIKA_PALETTE (viewable);
  gint         p_width;
  gint         p_height;

  if (! palette->n_colors)
    return FALSE;

  if (palette->n_columns)
    p_width = palette->n_columns;
  else
    p_width = MIN (palette->n_colors, 16);

  p_height = MAX (1, palette->n_colors / p_width);

  if (p_width * 4 > width || p_height * 4 > height)
    {
      *popup_width  = p_width  * 4;
      *popup_height = p_height * 4;

      return TRUE;
    }

  return FALSE;
}

static PikaTempBuf *
pika_palette_get_new_preview (PikaViewable *viewable,
                              PikaContext  *context,
                              gint          width,
                              gint          height)
{
  PikaPalette *palette  = PIKA_PALETTE (viewable);
  PikaTempBuf *temp_buf;
  guchar      *buf;
  guchar      *b;
  GList       *list;
  gint         columns;
  gint         rows;
  gint         cell_size;
  gint         x, y;

  temp_buf = pika_temp_buf_new (width, height, babl_format ("R'G'B' u8"));
  memset (pika_temp_buf_get_data (temp_buf), 255, width * height * 3);

  if (palette->n_columns > 1)
    cell_size = MAX (4, width / palette->n_columns);
  else
    cell_size = 4;

  columns = width  / cell_size;
  rows    = height / cell_size;

  buf = pika_temp_buf_get_data (temp_buf);
  b   = g_new (guchar, width * 3);

  list = palette->colors;

  for (y = 0; y < rows && list; y++)
    {
      gint i;

      memset (b, 255, width * 3);

      for (x = 0; x < columns && list; x++)
        {
          PikaPaletteEntry *entry = list->data;

          list = g_list_next (list);

          pika_rgb_get_uchar (&entry->color,
                              &b[x * cell_size * 3 + 0],
                              &b[x * cell_size * 3 + 1],
                              &b[x * cell_size * 3 + 2]);

          for (i = 1; i < cell_size; i++)
            {
              b[(x * cell_size + i) * 3 + 0] = b[(x * cell_size) * 3 + 0];
              b[(x * cell_size + i) * 3 + 1] = b[(x * cell_size) * 3 + 1];
              b[(x * cell_size + i) * 3 + 2] = b[(x * cell_size) * 3 + 2];
            }
        }

      for (i = 0; i < cell_size; i++)
        memcpy (buf + ((y * cell_size + i) * width) * 3, b, width * 3);
    }

  g_free (b);

  return temp_buf;
}

static gchar *
pika_palette_get_description (PikaViewable  *viewable,
                              gchar        **tooltip)
{
  PikaPalette *palette = PIKA_PALETTE (viewable);

  return g_strdup_printf ("%s (%d)",
                          pika_object_get_name (palette),
                          palette->n_colors);
}

PikaData *
pika_palette_new (PikaContext *context,
                  const gchar *name)
{
  g_return_val_if_fail (name != NULL, NULL);
  g_return_val_if_fail (*name != '\0', NULL);

  return g_object_new (PIKA_TYPE_PALETTE,
                       "name", name,
                       NULL);
}

PikaData *
pika_palette_get_standard (PikaContext *context)
{
  static PikaData *standard_palette = NULL;

  if (! standard_palette)
    {
      g_set_weak_pointer (&standard_palette,
                          pika_palette_new (context, "Standard"));

      pika_data_clean (standard_palette);
      pika_data_make_internal (standard_palette, "pika-palette-standard");
    }

  return standard_palette;
}

static const gchar *
pika_palette_get_extension (PikaData *data)
{
  return PIKA_PALETTE_FILE_EXTENSION;
}

static void
pika_palette_copy (PikaData *data,
                   PikaData *src_data)
{
  PikaPalette *palette     = PIKA_PALETTE (data);
  PikaPalette *src_palette = PIKA_PALETTE (src_data);
  GList       *list;

  pika_data_freeze (data);

  if (palette->colors)
    {
      g_list_free_full (palette->colors,
                        (GDestroyNotify) pika_palette_entry_free);
      palette->colors = NULL;
    }

  palette->n_colors  = 0;
  palette->n_columns = src_palette->n_columns;

  for (list = src_palette->colors; list; list = g_list_next (list))
    {
      PikaPaletteEntry *entry = list->data;

      pika_palette_add_entry (palette, -1, entry->name, &entry->color);
    }

  pika_data_thaw (data);
}

static void
pika_palette_real_entry_changed (PikaPalette *palette,
                                 gint         index)
{
  PikaImage *image = pika_data_get_image (PIKA_DATA (palette));

  if (image != NULL)
    pika_image_colormap_changed (image, index);
}

static gchar *
pika_palette_get_checksum (PikaTagged *tagged)
{
  PikaPalette *palette         = PIKA_PALETTE (tagged);
  gchar       *checksum_string = NULL;

  if (palette->n_colors > 0)
    {
      GChecksum *checksum       = g_checksum_new (G_CHECKSUM_MD5);
      GList     *color_iterator = palette->colors;

      g_checksum_update (checksum, (const guchar *) &palette->n_colors, sizeof (palette->n_colors));
      g_checksum_update (checksum, (const guchar *) &palette->n_columns, sizeof (palette->n_columns));

      while (color_iterator)
        {
          PikaPaletteEntry *entry = (PikaPaletteEntry *) color_iterator->data;

          g_checksum_update (checksum, (const guchar *) &entry->color, sizeof (entry->color));
          if (entry->name)
            g_checksum_update (checksum, (const guchar *) entry->name, strlen (entry->name));

          color_iterator = g_list_next (color_iterator);
        }

      checksum_string = g_strdup (g_checksum_get_string (checksum));

      g_checksum_free (checksum);
    }

  return checksum_string;
}


/*  public functions  */

GList *
pika_palette_get_colors (PikaPalette *palette)
{
  g_return_val_if_fail (PIKA_IS_PALETTE (palette), NULL);

  return palette->colors;
}

gint
pika_palette_get_n_colors (PikaPalette *palette)
{
  g_return_val_if_fail (PIKA_IS_PALETTE (palette), 0);

  return palette->n_colors;
}

void
pika_palette_move_entry (PikaPalette      *palette,
                         PikaPaletteEntry *entry,
                         gint              position)
{
  g_return_if_fail (PIKA_IS_PALETTE (palette));
  g_return_if_fail (entry != NULL);

  if (g_list_find (palette->colors, entry))
    {
      gint old_position = g_list_index (palette->colors, entry);

      palette->colors = g_list_remove (palette->colors,
                                       entry);
      palette->colors = g_list_insert (palette->colors,
                                       entry, position);

      if (! pika_data_is_frozen (PIKA_DATA (palette)))
        for (gint i = MIN (position, old_position); i <= MAX (position, old_position); i++)
          g_signal_emit (palette, signals[ENTRY_CHANGED], 0, i);

      pika_data_dirty (PIKA_DATA (palette));
    }
}

PikaPaletteEntry *
pika_palette_add_entry (PikaPalette   *palette,
                        gint           position,
                        const gchar   *name,
                        const PikaRGB *color)
{
  PikaPaletteEntry *entry;

  g_return_val_if_fail (PIKA_IS_PALETTE (palette), NULL);
  g_return_val_if_fail (color != NULL, NULL);

  entry = g_slice_new0 (PikaPaletteEntry);

  entry->color = *color;
  entry->name  = g_strdup (name ? name : _("Untitled"));

  if (position < 0 || position >= palette->n_colors)
    {
      palette->colors = g_list_append (palette->colors, entry);
    }
  else
    {
      palette->colors = g_list_insert (palette->colors, entry, position);
    }

  palette->n_colors += 1;

  if (! pika_data_is_frozen (PIKA_DATA (palette)))
    for (gint i = position; i < palette->n_colors; i++)
      g_signal_emit (palette, signals[ENTRY_CHANGED], 0, i);

  pika_data_dirty (PIKA_DATA (palette));

  return entry;
}

void
pika_palette_delete_entry (PikaPalette      *palette,
                           PikaPaletteEntry *entry)
{
  g_return_if_fail (PIKA_IS_PALETTE (palette));
  g_return_if_fail (entry != NULL);

  if (g_list_find (palette->colors, entry))
    {
      gint old_position = g_list_index (palette->colors, entry);

      pika_palette_entry_free (entry);

      palette->colors = g_list_remove (palette->colors, entry);

      palette->n_colors--;

      if (! pika_data_is_frozen (PIKA_DATA (palette)))
        for (gint i = old_position; i < palette->n_colors; i++)
          g_signal_emit (palette, signals[ENTRY_CHANGED], 0, i);

      pika_data_dirty (PIKA_DATA (palette));
    }
}

gboolean
pika_palette_set_entry (PikaPalette   *palette,
                        gint           position,
                        const gchar   *name,
                        const PikaRGB *color)
{
  PikaPaletteEntry *entry;

  g_return_val_if_fail (PIKA_IS_PALETTE (palette), FALSE);
  g_return_val_if_fail (color != NULL, FALSE);

  entry = pika_palette_get_entry (palette, position);

  if (! entry)
    return FALSE;

  entry->color = *color;

  if (entry->name)
    g_free (entry->name);

  entry->name = g_strdup (name);

  if (! pika_data_is_frozen (PIKA_DATA (palette)))
    g_signal_emit (palette, signals[ENTRY_CHANGED], 0, position);

  pika_data_dirty (PIKA_DATA (palette));

  return TRUE;
}

gboolean
pika_palette_set_entry_color (PikaPalette   *palette,
                              gint           position,
                              const PikaRGB *color,
                              gboolean       push_undo_if_image)
{
  PikaPaletteEntry *entry;

  g_return_val_if_fail (PIKA_IS_PALETTE (palette), FALSE);
  g_return_val_if_fail (color != NULL, FALSE);

  entry = pika_palette_get_entry (palette, position);

  if (! entry)
    return FALSE;

  if (push_undo_if_image && pika_data_get_image (PIKA_DATA (palette)))
    pika_image_undo_push_image_colormap (pika_data_get_image (PIKA_DATA (palette)),
                                         C_("undo-type", "Change Colormap entry"));

  entry->color = *color;

  if (! pika_data_is_frozen (PIKA_DATA (palette)))
    g_signal_emit (palette, signals[ENTRY_CHANGED], 0, position);

  pika_data_dirty (PIKA_DATA (palette));

  return TRUE;
}

gboolean
pika_palette_set_entry_name (PikaPalette *palette,
                             gint         position,
                             const gchar *name)
{
  PikaPaletteEntry *entry;

  g_return_val_if_fail (PIKA_IS_PALETTE (palette), FALSE);

  entry = pika_palette_get_entry (palette, position);

  if (! entry)
    return FALSE;

  if (entry->name)
    g_free (entry->name);

  entry->name = g_strdup (name);

  if (! pika_data_is_frozen (PIKA_DATA (palette)))
    g_signal_emit (palette, signals[ENTRY_CHANGED], 0, position);

  pika_data_dirty (PIKA_DATA (palette));

  return TRUE;
}

PikaPaletteEntry *
pika_palette_get_entry (PikaPalette *palette,
                        gint         position)
{
  g_return_val_if_fail (PIKA_IS_PALETTE (palette), NULL);

  return g_list_nth_data (palette->colors, position);
}

gint
pika_palette_get_entry_position (PikaPalette      *palette,
                                 PikaPaletteEntry *entry)
{
  g_return_val_if_fail (PIKA_IS_PALETTE (palette), -1);
  g_return_val_if_fail (entry != NULL, -1);

  return g_list_index (palette->colors, entry);
}

void
pika_palette_set_columns (PikaPalette *palette,
                          gint         columns)
{
  g_return_if_fail (PIKA_IS_PALETTE (palette));

  columns = CLAMP (columns, 0, 64);

  if (palette->n_columns != columns)
    {
      palette->n_columns = columns;

      pika_data_dirty (PIKA_DATA (palette));
    }
}

gint
pika_palette_get_columns (PikaPalette *palette)
{
  g_return_val_if_fail (PIKA_IS_PALETTE (palette), 0);

  return palette->n_columns;
}

PikaPaletteEntry *
pika_palette_find_entry (PikaPalette      *palette,
                         const PikaRGB    *color,
                         PikaPaletteEntry *start_from)
{
  PikaPaletteEntry *entry;

  g_return_val_if_fail (PIKA_IS_PALETTE (palette), NULL);
  g_return_val_if_fail (color != NULL, NULL);

  if (! start_from)
    {
      GList *list;

      /* search from the start */

      for (list = palette->colors; list; list = g_list_next (list))
        {
          entry = (PikaPaletteEntry *) list->data;
          if (pika_rgb_distance (&entry->color, color) < RGB_EPSILON)
            return entry;
        }
    }
  else if (pika_rgb_distance (&start_from->color, color) < RGB_EPSILON)
    {
      return start_from;
    }
  else
    {
      GList *old = g_list_find (palette->colors, start_from);
      GList *next;
      GList *prev;

      g_return_val_if_fail (old != NULL, NULL);

      next = old->next;
      prev = old->prev;

      /* proximity-based search */

      while (next || prev)
        {
          if (next)
            {
              entry = (PikaPaletteEntry *) next->data;
              if (pika_rgb_distance (&entry->color, color) < RGB_EPSILON)
                return entry;

              next = next->next;
            }

          if (prev)
            {
              entry = (PikaPaletteEntry *) prev->data;
              if (pika_rgb_distance (&entry->color, color) < RGB_EPSILON)
                return entry;

              prev = prev->prev;
            }
        }
    }

  return NULL;
}


/*  private functions  */

static void
pika_palette_entry_free (PikaPaletteEntry *entry)
{
  g_return_if_fail (entry != NULL);

  g_free (entry->name);

  g_slice_free (PikaPaletteEntry, entry);
}

static gint64
pika_palette_entry_get_memsize (PikaPaletteEntry *entry,
                                gint64           *gui_size)
{
  gint64 memsize = sizeof (PikaPaletteEntry);

  memsize += pika_string_get_memsize (entry->name);

  return memsize;
}
