/* borderaverage 0.01 - image processing plug-in for PIKA.
 *
 * Copyright (C) 1998 Philipp Klaus (webmaster@access.ch)
 *
 *
 * 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 <libpika/pika.h>
#include <libpika/pikaui.h>

#include "libpika/stdplugins-intl.h"


#define PLUG_IN_PROC   "plug-in-borderaverage"
#define PLUG_IN_BINARY "border-average"
#define PLUG_IN_ROLE   "pika-border-average"


typedef struct _BorderAverage      BorderAverage;
typedef struct _BorderAverageClass BorderAverageClass;

struct _BorderAverage
{
  PikaPlugIn      parent_instance;
};

struct _BorderAverageClass
{
  PikaPlugInClass parent_class;
};


#define BORDER_AVERAGE_TYPE  (border_average_get_type ())
#define BORDER_AVERAGE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), BORDER_AVERAGE_TYPE, BorderAverage))


GType                   border_average_get_type               (void) G_GNUC_CONST;

static GList          * border_average_query_procedures       (PikaPlugIn           *plug_in);
static PikaProcedure  * border_average_create_procedure       (PikaPlugIn           *plug_in,
                                                               const gchar          *name);

static PikaValueArray * border_average_run                    (PikaProcedure        *procedure,
                                                               PikaRunMode           run_mode,
                                                               PikaImage            *image,
                                                               gint                  n_drawables,
                                                               PikaDrawable        **drawables,
                                                               PikaProcedureConfig  *config,
                                                               gpointer              run_data);


static void      borderaverage        (GObject      *config,
                                       GeglBuffer   *buffer,
                                       PikaDrawable *drawable,
                                       PikaRGB      *result);

static gboolean  borderaverage_dialog (PikaProcedure *procedure,
                                       GObject       *config,
                                       PikaImage     *image,
                                       PikaDrawable  *drawable);

static void      add_new_color        (const guchar *buffer,
                                       gint         *cube,
                                       gint          bucket_expo);


G_DEFINE_TYPE (BorderAverage, border_average, PIKA_TYPE_PLUG_IN)

PIKA_MAIN (BORDER_AVERAGE_TYPE)
DEFINE_STD_SET_I18N


static void
border_average_class_init (BorderAverageClass *klass)
{
  PikaPlugInClass *plug_in_class = PIKA_PLUG_IN_CLASS (klass);

  plug_in_class->query_procedures = border_average_query_procedures;
  plug_in_class->create_procedure = border_average_create_procedure;
  plug_in_class->set_i18n         = STD_SET_I18N;
}

static void
border_average_init (BorderAverage *film)
{
}

static GList *
border_average_query_procedures (PikaPlugIn *plug_in)
{
  return g_list_append (NULL, g_strdup (PLUG_IN_PROC));
}

static PikaProcedure *
border_average_create_procedure (PikaPlugIn  *plug_in,
                                 const gchar *name)
{
  PikaProcedure *procedure = NULL;

  if (! strcmp (name, PLUG_IN_PROC))
    {
      procedure = pika_image_procedure_new (plug_in, name,
                                            PIKA_PDB_PROC_TYPE_PLUGIN,
                                            border_average_run, NULL, NULL);

      pika_procedure_set_image_types (procedure, "RGB*");
      pika_procedure_set_sensitivity_mask (procedure,
                                           PIKA_PROCEDURE_SENSITIVE_DRAWABLE);

      pika_procedure_set_menu_label (procedure, _("_Border Average..."));
      pika_procedure_add_menu_path (procedure, "<Image>/Colors/Info");

      pika_procedure_set_documentation (procedure,
                                        _("Set foreground to the average color of the image border"),
                                        "",
                                        name);
      pika_procedure_set_attribution (procedure,
                                      "Philipp Klaus",
                                      "Internet Access AG",
                                      "1998");

      PIKA_PROC_ARG_INT (procedure, "thickness",
                         _("_Thickness"),
                         _("Border size to take in count"),
                         0, G_MAXINT, 3,
                         G_PARAM_READWRITE);
      PIKA_PROC_AUX_ARG_UNIT (procedure, "thickness-unit",
                              _("Thickness unit of measure"),
                              _("Border size unit of measure"),
                              TRUE, TRUE, PIKA_UNIT_PIXEL,
                              PIKA_PARAM_READWRITE);
      PIKA_PROC_ARG_INT (procedure, "bucket-exponent",
                         _("Bucket Si_ze"),
                         _("Bits for bucket size (default=4: 16 Levels)"),
                         0, G_MAXINT, 4,
                         G_PARAM_READWRITE);

      PIKA_PROC_VAL_RGB (procedure, "borderaverage",
                         _("The average color of the specified border."),
                         _("The average color of the specified border."),
                         TRUE, NULL,
                         G_PARAM_READWRITE);
    }

  return procedure;
}


static PikaValueArray *
border_average_run (PikaProcedure        *procedure,
                    PikaRunMode           run_mode,
                    PikaImage            *image,
                    gint                  n_drawables,
                    PikaDrawable        **drawables,
                    PikaProcedureConfig  *config,
                    gpointer              run_data)
{
  PikaDrawable      *drawable;
  PikaValueArray    *return_vals = NULL;
  PikaPDBStatusType  status = PIKA_PDB_SUCCESS;
  PikaRGB            result_color = { 0.0, };
  GeglBuffer        *buffer;

  gegl_init (NULL, NULL);

  if (n_drawables != 1)
    {
      GError *error = NULL;

      g_set_error (&error, PIKA_PLUG_IN_ERROR, 0,
                   _("Procedure '%s' only works with one drawable."),
                   PLUG_IN_PROC);

      return pika_procedure_new_return_values (procedure,
                                               PIKA_PDB_CALLING_ERROR,
                                               error);
    }
  else
    {
      drawable = drawables[0];
    }

  buffer = pika_drawable_get_buffer (drawable);

  if (run_mode == PIKA_RUN_INTERACTIVE &&
      ! borderaverage_dialog (procedure, G_OBJECT (config), image, drawable))
    return pika_procedure_new_return_values (procedure, PIKA_PDB_CANCEL, NULL);

  if (status == PIKA_PDB_SUCCESS)
    {
      /*  Make sure that the drawable is RGB color  */
      if (pika_drawable_is_rgb (drawable))
        {
          pika_progress_init ( _("Border Average"));
          borderaverage (G_OBJECT (config), buffer, drawable, &result_color);

          if (run_mode != PIKA_RUN_NONINTERACTIVE)
            pika_context_set_foreground (&result_color);
        }
      else
        {
          status = PIKA_PDB_EXECUTION_ERROR;
        }
    }

  g_object_unref (buffer);

  return_vals = pika_procedure_new_return_values (procedure, status, NULL);

  if (status == PIKA_PDB_SUCCESS)
    PIKA_VALUES_SET_RGB (return_vals, 1, &result_color);

  return return_vals;
}


static void
borderaverage (GObject      *config,
               GeglBuffer   *buffer,
               PikaDrawable *drawable,
               PikaRGB      *result)
{
  gint            x, y, width, height;
  gint            max;
  guchar          r, g, b;
  gint            bucket_num, bucket_expo, bucket_rexpo;
  gint           *cube;
  gint            i, j, k;
  GeglRectangle   border[4];
  gint            borderaverage_thickness;
  gint            borderaverage_bucket_exponent;

  g_object_get (config,
                "thickness", &borderaverage_thickness,
                "bucket-exponent", &borderaverage_bucket_exponent,
                NULL);

  if (! pika_drawable_mask_intersect (drawable, &x, &y, &width, &height))
    {
      pika_rgba_set_uchar (result, 0, 0, 0, 255);
      return;
    }

  /* allocate and clear the cube before */
  bucket_expo = borderaverage_bucket_exponent;
  bucket_rexpo = 8 - bucket_expo;
  cube = g_new (gint, 1 << (bucket_rexpo * 3));
  bucket_num = 1 << bucket_rexpo;

  for (i = 0; i < bucket_num; i++)
    {
      for (j = 0; j < bucket_num; j++)
        {
          for (k = 0; k < bucket_num; k++)
            {
              cube[(i << (bucket_rexpo << 1)) + (j << bucket_rexpo) + k] = 0;
            }
        }
    }

  /* Top */
  border[0].x =       x;
  border[0].y =       y;
  border[0].width =   width;
  border[0].height =  borderaverage_thickness;

  /* Bottom */
  border[1].x =       x;
  border[1].y =       y + height - borderaverage_thickness;
  border[1].width =   width;
  border[1].height =  borderaverage_thickness;

  /* Left */
  border[2].x =       x;
  border[2].y =       y + borderaverage_thickness;
  border[2].width =   borderaverage_thickness;
  border[2].height =  height - 2 * borderaverage_thickness;

  /* Right */
  border[3].x =       x + width - borderaverage_thickness;
  border[3].y =       y + borderaverage_thickness;
  border[3].width =   borderaverage_thickness;
  border[3].height =  height - 2 * borderaverage_thickness;

  /* Fill the cube */
  for (i = 0; i < 4; i++)
    {
      if (border[i].width > 0 && border[i].height > 0)
        {
          GeglBufferIterator *gi;

          gi = gegl_buffer_iterator_new (buffer, &border[i], 0, babl_format ("R'G'B' u8"),
                                         GEGL_ACCESS_READWRITE, GEGL_ABYSS_NONE, 1);

          while (gegl_buffer_iterator_next (gi))
            {
              guint   k;
              guchar *data;

              data = (guchar*) gi->items[0].data;

              for (k = 0; k < gi->length; k++)
                {
                  add_new_color (data + k * 3,
                                 cube,
                                 bucket_expo);
                }
            }
        }
    }

  max = 0; r = 0; g = 0; b = 0;

  /* get max of cube */
  for (i = 0; i < bucket_num; i++)
    {
      for (j = 0; j < bucket_num; j++)
        {
          for (k = 0; k < bucket_num; k++)
            {
              if (cube[(i << (bucket_rexpo << 1)) +
                      (j << bucket_rexpo) + k] > max)
                {
                  max = cube[(i << (bucket_rexpo << 1)) +
                             (j << bucket_rexpo) + k];
                  r = (i<<bucket_expo) + (1<<(bucket_expo - 1));
                  g = (j<<bucket_expo) + (1<<(bucket_expo - 1));
                  b = (k<<bucket_expo) + (1<<(bucket_expo - 1));
                }
            }
        }
    }

  /* return the color */
  pika_rgba_set_uchar (result, r, g, b, 255);

  g_free (cube);
}

static void
add_new_color (const guchar *buffer,
               gint         *cube,
               gint          bucket_expo)
{
  guchar r, g, b;
  gint   bucket_rexpo;

  bucket_rexpo = 8 - bucket_expo;
  r = buffer[0] >> bucket_expo;
  g = buffer[1] >> bucket_expo;
  b = buffer[2] >> bucket_expo;
  cube[(r << (bucket_rexpo << 1)) + (g << bucket_rexpo) + b]++;
}

static gboolean
borderaverage_dialog (PikaProcedure *procedure,
                      GObject       *config,
                      PikaImage     *image,
                      PikaDrawable  *drawable)
{
  GtkWidget    *dialog;
  GtkListStore *store;
  GtkWidget    *size_entry;
  gboolean      run;
  gdouble       xres, yres;
  GeglBuffer   *buffer = NULL;

  pika_ui_init (PLUG_IN_BINARY);

  dialog = pika_procedure_dialog_new (procedure,
                                      PIKA_PROCEDURE_CONFIG (config),
                                      _("Border Average"));

  pika_dialog_set_alternative_button_order (GTK_DIALOG (dialog),
                                           GTK_RESPONSE_OK,
                                           GTK_RESPONSE_CANCEL,
                                           -1);

  pika_window_set_transient (GTK_WINDOW (dialog));

  pika_procedure_dialog_get_label (PIKA_PROCEDURE_DIALOG (dialog),
                                   "border-size-label",
                                   _("Border Size"),
                                   FALSE, FALSE);

  /*  Get the image resolution  */
  pika_image_get_resolution (image, &xres, &yres);
  size_entry = pika_procedure_dialog_get_size_entry (PIKA_PROCEDURE_DIALOG (dialog),
                                                     "thickness", TRUE,
                                                     "thickness-unit", "%a",
                                                     PIKA_SIZE_ENTRY_UPDATE_SIZE,
                                                     xres);

  /*  set the size (in pixels) that will be treated as 0% and 100%  */
  buffer = pika_drawable_get_buffer (drawable);
  if (buffer)
    pika_size_entry_set_size (PIKA_SIZE_ENTRY (size_entry), 0, 0.0,
                              MIN (gegl_buffer_get_width (buffer),
                                   gegl_buffer_get_height (buffer)));
  pika_size_entry_set_refval_boundaries (PIKA_SIZE_ENTRY (size_entry), 0, 1.0,
                                         MIN (gegl_buffer_get_width (buffer),
                                              gegl_buffer_get_height (buffer)) / 2);

  pika_procedure_dialog_fill_frame (PIKA_PROCEDURE_DIALOG (dialog),
                                    "border-size-frame", "border-size-label",
                                    FALSE, "thickness");

  pika_procedure_dialog_get_label (PIKA_PROCEDURE_DIALOG (dialog),
                                   "bucket-size-label",
                                   _("Number of Colors"),
                                   FALSE, FALSE);

  store = pika_int_store_new ("1",   0, "2",   1, "4",   2, "8",   3,
                              "16",  4, "32",  5, "64",  6, "128", 7,
                              "256", 8, NULL);
  pika_procedure_dialog_get_int_combo (PIKA_PROCEDURE_DIALOG (dialog),
                                       "bucket-exponent",
                                       PIKA_INT_STORE (store));

  pika_procedure_dialog_fill_frame (PIKA_PROCEDURE_DIALOG (dialog),
                                    "bucket-size-frame", "bucket-size-label",
                                    FALSE, "bucket-exponent");

  pika_procedure_dialog_fill (PIKA_PROCEDURE_DIALOG (dialog),
                              "border-size-frame",
                              "bucket-size-frame",
                              NULL);

  gtk_widget_show (dialog);

  run = pika_procedure_dialog_run (PIKA_PROCEDURE_DIALOG (dialog));

  gtk_widget_destroy (dialog);

  return run;
}
