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

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

#include "core/core-types.h"

#include "core/pika.h"
#include "core/pikabrush.h"
#include "core/pikabrush-load.h"
#include "core/pikabrush-private.h"
#include "core/pikacontainer.h"
#include "core/pikadrawable.h"
#include "core/pikaimage.h"
#include "core/pikaimage-merge.h"
#include "core/pikaimage-new.h"
#include "core/pikaimage-resize.h"
#include "core/pikalayer-new.h"
#include "core/pikaparamspecs.h"
#include "core/pikapickable.h"
#include "core/pikatempbuf.h"

#include "pdb/pikaprocedure.h"

#include "file-data-gbr.h"

#include "pika-intl.h"


/*  local function prototypes  */

static PikaImage * file_gbr_brush_to_image (Pika          *pika,
                                            PikaBrush     *brush);
static PikaBrush * file_gbr_image_to_brush (PikaImage     *image,
                                            PikaContext   *context,
                                            gint           n_drawables,
                                            PikaDrawable **drawables,
                                            const gchar   *name,
                                            gdouble        spacing);


/*  public functions  */

PikaValueArray *
file_gbr_load_invoker (PikaProcedure         *procedure,
                       Pika                  *pika,
                       PikaContext           *context,
                       PikaProgress          *progress,
                       const PikaValueArray  *args,
                       GError               **error)
{
  PikaValueArray *return_vals;
  PikaImage      *image = NULL;
  GFile          *file;
  GInputStream   *input;
  GError         *my_error = NULL;

  pika_set_busy (pika);

  file = g_value_get_object (pika_value_array_index (args, 1));

  input = G_INPUT_STREAM (g_file_read (file, NULL, &my_error));

  if (input)
    {
      PikaBrush *brush = pika_brush_load_brush (context, file, input, error);

      if (brush)
        {
          image = file_gbr_brush_to_image (pika, brush);
          g_object_unref (brush);
        }

      g_object_unref (input);
    }
  else
    {
      g_propagate_prefixed_error (error, my_error,
                                  _("Could not open '%s' for reading: "),
                                  pika_file_get_utf8_name (file));
    }

  return_vals = pika_procedure_get_return_values (procedure, image != NULL,
                                                  error ? *error : NULL);

  if (image)
    g_value_set_object (pika_value_array_index (return_vals, 1), image);

  pika_unset_busy (pika);

  return return_vals;
}

PikaValueArray *
file_gbr_save_invoker (PikaProcedure         *procedure,
                       Pika                  *pika,
                       PikaContext           *context,
                       PikaProgress          *progress,
                       const PikaValueArray  *args,
                       GError               **error)
{
  PikaValueArray  *return_vals;
  PikaImage       *image;
  PikaDrawable   **drawables;
  gint             n_drawables;
  PikaBrush       *brush;
  const gchar     *name;
  GFile           *file;
  gint             spacing;
  gboolean         success;

  pika_set_busy (pika);

  image       = g_value_get_object (pika_value_array_index (args, 1));
  n_drawables = g_value_get_int (pika_value_array_index (args, 2));
  drawables   = (PikaDrawable **) pika_value_get_object_array (pika_value_array_index (args, 3));
  file        = g_value_get_object (pika_value_array_index (args, 4));
  spacing     = g_value_get_int    (pika_value_array_index (args, 5));
  name        = g_value_get_string (pika_value_array_index (args, 6));

  brush = file_gbr_image_to_brush (image, context, n_drawables, drawables, name, spacing);

  pika_data_set_file (PIKA_DATA (brush), file, TRUE, TRUE);

  success = pika_data_save (PIKA_DATA (brush), error);

  g_object_unref (brush);

  return_vals = pika_procedure_get_return_values (procedure, success,
                                                  error ? *error : NULL);

  pika_unset_busy (pika);

  return return_vals;
}

PikaLayer *
file_gbr_brush_to_layer (PikaImage *image,
                         PikaBrush *brush)
{
  PikaLayer    *layer;
  const Babl   *format;
  gboolean      alpha;
  gint          width;
  gint          height;
  gint          image_width;
  gint          image_height;
  PikaTempBuf  *mask;
  PikaTempBuf  *pixmap;
  GeglBuffer   *buffer;

  g_return_val_if_fail (PIKA_IS_IMAGE (image), NULL);
  g_return_val_if_fail (PIKA_IS_BRUSH (brush), NULL);

  mask   = pika_brush_get_mask   (brush);
  pixmap = pika_brush_get_pixmap (brush);

  if (pixmap)
    alpha = TRUE;
  else
    alpha = FALSE;

  width  = pika_temp_buf_get_width  (mask);
  height = pika_temp_buf_get_height (mask);

  image_width  = pika_image_get_width  (image);
  image_height = pika_image_get_height (image);

  if (width > image_width || height > image_height)
    {
      gint new_width  = MAX (image_width,  width);
      gint new_height = MAX (image_height, height);

      pika_image_resize (image, pika_get_user_context (image->pika),
                         new_width, new_height,
                         (new_width  - image_width) / 2,
                         (new_height - image_height) / 2,
                         NULL);

      image_width  = new_width;
      image_height = new_height;
    }

  format = pika_image_get_layer_format (image, alpha);

  layer = pika_layer_new (image, width, height, format,
                          pika_object_get_name (brush),
                          1.0, PIKA_LAYER_MODE_NORMAL);

  pika_item_set_offset (PIKA_ITEM (layer),
                        (image_width  - width)  / 2,
                        (image_height - height) / 2);

  buffer = pika_drawable_get_buffer (PIKA_DRAWABLE (layer));

  if (pixmap)
    {
      guchar *pixmap_data;
      guchar *mask_data;
      guchar *p;
      guchar *m;
      gint    i;

      gegl_buffer_set (buffer, GEGL_RECTANGLE (0, 0, width, height), 0,
                       babl_format ("R'G'B' u8"),
                       pika_temp_buf_get_data (pixmap), GEGL_AUTO_ROWSTRIDE);

      pixmap_data = gegl_buffer_linear_open (buffer, NULL, NULL, NULL);
      mask_data   = pika_temp_buf_get_data (mask);

      for (i = 0, p = pixmap_data, m = mask_data;
           i < width * height;
           i++, p += 4, m += 1)
        {
          p[3] = *m;
        }

      gegl_buffer_linear_close (buffer, pixmap_data);
    }
  else
    {
      guchar *mask_data = pika_temp_buf_get_data (mask);
      gint    i;

      for (i = 0; i < width * height; i++)
        mask_data[i] = 255 - mask_data[i];

      gegl_buffer_set (buffer, GEGL_RECTANGLE (0, 0, width, height), 0,
                       babl_format ("Y' u8"),
                       mask_data, GEGL_AUTO_ROWSTRIDE);
    }

  return layer;
}

PikaBrush *
file_gbr_drawable_to_brush (PikaDrawable        *drawable,
                            const GeglRectangle *rect,
                            const gchar         *name,
                            gdouble              spacing)
{
  PikaBrush   *brush;
  GeglBuffer  *buffer;
  PikaTempBuf *mask;
  PikaTempBuf *pixmap = NULL;
  gint         width;
  gint         height;

  g_return_val_if_fail (PIKA_IS_DRAWABLE (drawable), NULL);
  g_return_val_if_fail (rect != NULL, NULL);

  buffer = pika_drawable_get_buffer (drawable);
  width  = rect->width;
  height = rect->height;

  brush = g_object_new (PIKA_TYPE_BRUSH,
                        "name",      name,
                        "mime-type", "image/x-pika-gbr",
                        "spacing",   spacing,
                        NULL);

  mask = pika_temp_buf_new (width, height, babl_format ("Y u8"));

  if (pika_drawable_is_gray (drawable))
    {
      guchar *m = pika_temp_buf_get_data (mask);
      gint    i;

      if (pika_drawable_has_alpha (drawable))
        {
          GeglBufferIterator *iter;
          PikaRGB             white;

          pika_rgba_set_uchar (&white, 255, 255, 255, 255);

          iter = gegl_buffer_iterator_new (buffer, rect, 0,
                                           babl_format ("Y'A u8"),
                                           GEGL_ACCESS_READ, GEGL_ABYSS_NONE,
                                           1);

          while (gegl_buffer_iterator_next (iter))
            {
              guint8 *data = (guint8 *) iter->items[0].data;
              gint    j;

              for (j = 0; j < iter->length; j++)
                {
                  PikaRGB gray;
                  gint    x, y;
                  gint    dest;

                  pika_rgba_set_uchar (&gray,
                                       data[0], data[0], data[0],
                                       data[1]);

                  pika_rgb_composite (&gray, &white,
                                      PIKA_RGB_COMPOSITE_BEHIND);

                  x = iter->items[0].roi.x + j % iter->items[0].roi.width;
                  y = iter->items[0].roi.y + j / iter->items[0].roi.width;

                  dest = y * width + x;

                  pika_rgba_get_uchar (&gray, &m[dest], NULL, NULL, NULL);

                  data += 2;
                }
            }
        }
      else
        {
          gegl_buffer_get (buffer, rect, 1.0,
                           babl_format ("Y' u8"), m,
                           GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
        }

      /*  invert  */
      for (i = 0; i < width * height; i++)
        m[i] = 255 - m[i];
    }
  else
    {
      pixmap = pika_temp_buf_new (width, height, babl_format ("R'G'B' u8"));

      gegl_buffer_get (buffer, rect, 1.0,
                       babl_format ("R'G'B' u8"),
                       pika_temp_buf_get_data (pixmap),
                       GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);

      gegl_buffer_get (buffer, rect, 1.0,
                       babl_format ("A u8"),
                       pika_temp_buf_get_data (mask),
                       GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
    }


  brush->priv->mask   = mask;
  brush->priv->pixmap = pixmap;

  return brush;
}


/*  private functions  */

static PikaImage *
file_gbr_brush_to_image (Pika      *pika,
                         PikaBrush *brush)
{
  PikaImage         *image;
  PikaLayer         *layer;
  PikaImageBaseType  base_type;
  gint               width;
  gint               height;
  PikaTempBuf       *mask   = pika_brush_get_mask   (brush);
  PikaTempBuf       *pixmap = pika_brush_get_pixmap (brush);
  GString           *string;
  PikaConfigWriter  *writer;
  PikaParasite      *parasite;

  if (pixmap)
    base_type = PIKA_RGB;
  else
    base_type = PIKA_GRAY;

  width  = pika_temp_buf_get_width  (mask);
  height = pika_temp_buf_get_height (mask);

  image = pika_image_new (pika, width, height, base_type,
                          PIKA_PRECISION_U8_NON_LINEAR);

  string = g_string_new (NULL);
  writer = pika_config_writer_new_from_string (string);

  pika_config_writer_open (writer, "spacing");
  pika_config_writer_printf (writer, "%d", pika_brush_get_spacing (brush));
  pika_config_writer_close (writer);

  pika_config_writer_linefeed (writer);

  pika_config_writer_open (writer, "description");
  pika_config_writer_string (writer, pika_object_get_name (brush));
  pika_config_writer_close (writer);

  pika_config_writer_finish (writer, NULL, NULL);

  parasite = pika_parasite_new ("PikaProcedureConfig-file-gbr-save-last",
                                PIKA_PARASITE_PERSISTENT,
                                string->len + 1, string->str);
  pika_image_parasite_attach (image, parasite, FALSE);
  pika_parasite_free (parasite);

  g_string_free (string, TRUE);

  layer = file_gbr_brush_to_layer (image, brush);
  pika_image_add_layer (image, layer, NULL, 0, FALSE);

  return image;
}

static PikaBrush *
file_gbr_image_to_brush (PikaImage     *image,
                         PikaContext   *context,
                         gint           n_drawables,
                         PikaDrawable **drawables,
                         const gchar   *name,
                         gdouble        spacing)
{
  PikaBrush    *brush;
  PikaImage    *subimage = NULL;
  PikaDrawable *drawable;
  gint          width;
  gint          height;

  g_return_val_if_fail (n_drawables > 0, NULL);
  g_return_val_if_fail (drawables != NULL, NULL);

  if (n_drawables > 1)
    {
      GList *drawable_list = NULL;

      for (gint i = 0; i < n_drawables; i++)
        drawable_list = g_list_prepend (drawable_list, drawables[i]);

      subimage = pika_image_new_from_drawables (image->pika, drawable_list, FALSE, FALSE);
      g_list_free (drawable_list);
      pika_container_remove (image->pika->images, PIKA_OBJECT (subimage));
      pika_image_resize_to_layers (subimage, context,
                                   NULL, NULL, NULL, NULL, NULL);
      drawable = PIKA_DRAWABLE (pika_image_merge_visible_layers (subimage, context, PIKA_CLIP_TO_IMAGE,
                                                                 FALSE, TRUE, NULL));
      pika_pickable_flush (PIKA_PICKABLE (subimage));
    }
  else
    {
      drawable = drawables[0];
    }
  width  = pika_item_get_width  (PIKA_ITEM (drawable));
  height = pika_item_get_height (PIKA_ITEM (drawable));

  brush = file_gbr_drawable_to_brush (drawable,
                                      GEGL_RECTANGLE (0, 0, width, height),
                                      name, spacing);
  g_clear_object (&subimage);

  return brush;
}
