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

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

#include "core/core-types.h"

#include "gegl/pika-babl.h"

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

#include "pdb/pikaprocedure.h"

#include "file-data-pat.h"

#include "pika-intl.h"


/*  local function prototypes  */

static PikaImage   * file_pat_pattern_to_image (Pika          *pika,
                                                PikaPattern   *pattern);
static PikaPattern * file_pat_image_to_pattern (PikaImage     *image,
                                                PikaContext   *context,
                                                gint           n_drawables,
                                                PikaDrawable **drawables,
                                                const gchar   *name);


/*  public functions  */

PikaValueArray *
file_pat_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)
    {
      GList *list = pika_pattern_load (context, file, input, error);

      if (list)
        {
          PikaPattern *pattern = list->data;

          g_list_free (list);

          image = file_pat_pattern_to_image (pika, pattern);
          g_object_unref (pattern);
        }

      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_pat_save_invoker (PikaProcedure         *procedure,
                       Pika                  *pika,
                       PikaContext           *context,
                       PikaProgress          *progress,
                       const PikaValueArray  *args,
                       GError               **error)
{
  PikaValueArray  *return_vals;
  PikaImage       *image;
  PikaPattern     *pattern;
  const gchar     *name;
  GFile           *file;
  PikaDrawable   **drawables;
  gint             n_drawables;
  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));
  name        = g_value_get_string (pika_value_array_index (args, 5));

  pattern = file_pat_image_to_pattern (image, context, n_drawables, drawables, name);

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

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

  g_object_unref (pattern);

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

  pika_unset_busy (pika);

  return return_vals;
}


/*  private functions  */

static PikaImage *
file_pat_pattern_to_image (Pika        *pika,
                           PikaPattern *pattern)
{
  PikaImage         *image;
  PikaLayer         *layer;
  const Babl        *format;
  PikaImageBaseType  base_type;
  gboolean           alpha;
  gint               width;
  gint               height;
  PikaTempBuf       *mask   = pika_pattern_get_mask (pattern);
  GeglBuffer        *buffer;
  GString           *string;
  PikaConfigWriter  *writer;
  PikaParasite      *parasite;

  format = pika_temp_buf_get_format (mask);

  switch (babl_format_get_bytes_per_pixel (format))
    {
    case 1:
      base_type = PIKA_GRAY;
      alpha     = FALSE;
      break;

    case 2:
      base_type = PIKA_GRAY;
      alpha     = TRUE;
      break;

    case 3:
      base_type = PIKA_RGB;
      alpha     = FALSE;
      break;

    case 4:
      base_type = PIKA_RGB;
      alpha     = TRUE;
      break;

    default:
      g_return_val_if_reached (NULL);
    }

  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, "description");
  pika_config_writer_string (writer, pika_object_get_name (pattern));
  pika_config_writer_close (writer);

  pika_config_writer_finish (writer, NULL, NULL);

  parasite = pika_parasite_new ("PikaProcedureConfig-file-pat-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);

  format = pika_image_get_layer_format (image, alpha);

  layer = pika_layer_new (image, width, height, format,
                          pika_object_get_name (pattern),
                          1.0, PIKA_LAYER_MODE_NORMAL);
  pika_image_add_layer (image, layer, NULL, 0, FALSE);

  buffer = pika_drawable_get_buffer (PIKA_DRAWABLE (layer));

  gegl_buffer_set (buffer, GEGL_RECTANGLE (0, 0, width, height), 0,
                   NULL,
                   pika_temp_buf_get_data (mask), GEGL_AUTO_ROWSTRIDE);

  return image;
}

static PikaPattern *
file_pat_image_to_pattern (PikaImage     *image,
                           PikaContext   *context,
                           gint           n_drawables,
                           PikaDrawable **drawables,
                           const gchar   *name)
{
  PikaPattern *pattern;
  PikaImage   *subimage = NULL;
  const Babl  *format;
  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);
      width  = pika_image_get_width (subimage);
      height = pika_image_get_width (subimage);

      pika_pickable_flush (PIKA_PICKABLE (subimage));
    }
  else
    {
      width  = pika_item_get_width  (PIKA_ITEM (drawables[0]));
      height = pika_item_get_height (PIKA_ITEM (drawables[0]));
    }

  format = pika_babl_format (pika_drawable_is_gray (drawables[0]) ?
                             PIKA_GRAY : PIKA_RGB,
                             PIKA_PRECISION_U8_NON_LINEAR,
                             (subimage && pika_image_has_alpha (subimage)) ||
                             pika_drawable_has_alpha (drawables[0]),
                             NULL);

  pattern = g_object_new (PIKA_TYPE_PATTERN,
                          "name",      name,
                          "mime-type", "image/x-pika-pat",
                          NULL);

  pattern->mask = pika_temp_buf_new (width, height, format);

  gegl_buffer_get (subimage != NULL ? pika_pickable_get_buffer (PIKA_PICKABLE (subimage)) :
                                      pika_drawable_get_buffer (drawables[0]),
                   GEGL_RECTANGLE (0, 0, width, height), 1.0,
                   format, pika_temp_buf_get_data (pattern->mask),
                   GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);

  g_clear_object (&subimage);

  return pattern;
}
