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

#include "libpikabase/pikabase.h"
#include "libpikawidgets/pikawidgets.h"

#include "actions-types.h"

#include "config/pikaguiconfig.h"

#include "core/pika.h"
#include "core/pikacontainer.h"
#include "core/pikaimage.h"
#include "core/pikaimagefile.h"
#include "core/pikaviewable.h"

#include "file/pika-file.h"

#include "plug-in/pikapluginmanager-file.h"

#include "widgets/pikaaction.h"
#include "widgets/pikaactiongroup.h"
#include "widgets/pikaactionimpl.h"
#include "widgets/pikahelp-ids.h"

#include "display/pikadisplay.h"

#include "actions.h"
#include "file-actions.h"
#include "file-commands.h"

#include "pika-intl.h"


/*  local function prototypes  */

static void    file_actions_last_opened_update  (PikaContainer   *container,
                                                 PikaImagefile   *unused,
                                                 PikaActionGroup *group);
static void    file_actions_last_opened_reorder (PikaContainer   *container,
                                                 PikaImagefile   *unused1,
                                                 gint             unused2,
                                                 PikaActionGroup *group);
static void    file_actions_close_all_update    (PikaContainer   *images,
                                                 PikaObject      *unused,
                                                 PikaActionGroup *group);
static gchar * file_actions_create_label        (const gchar     *format,
                                                 GFile           *file);


static const PikaActionEntry file_actions[] =
{
  { "file-open", PIKA_ICON_IMAGE_OPEN,
    NC_("file-action", "_Open..."), NULL, { "<primary>O", NULL },
    NC_("file-action", "Open an image file"),
    file_open_cmd_callback,
    PIKA_HELP_FILE_OPEN },

  { "file-open-as-layers", PIKA_ICON_LAYER,
    NC_("file-action", "Op_en as Layers..."), NULL, { "<primary><alt>O", NULL },
    NC_("file-action", "Open an image file as layers"),
    file_open_as_layers_cmd_callback,
    PIKA_HELP_FILE_OPEN_AS_LAYER },

  { "file-open-location", PIKA_ICON_WEB,
    NC_("file-action", "Open _Location..."), NULL, { NULL },
    NC_("file-action", "Open an image file from a specified location"),
    file_open_location_cmd_callback,
    PIKA_HELP_FILE_OPEN_LOCATION },

  { "file-create-template", NULL,
    NC_("file-action", "Create _Template..."), NULL, { NULL },
    NC_("file-action", "Create a new template from this image"),
    file_create_template_cmd_callback,
    PIKA_HELP_FILE_CREATE_TEMPLATE },

  { "file-revert", PIKA_ICON_IMAGE_RELOAD,
    NC_("file-action", "Re_vert"), NULL, { NULL },
    NC_("file-action", "Reload the image file from disk"),
    file_revert_cmd_callback,
    PIKA_HELP_FILE_REVERT },

  { "file-close-all", PIKA_ICON_CLOSE_ALL,
    NC_("file-action", "C_lose All"), NULL, { "<primary><shift>W", NULL },
    NC_("file-action", "Close all opened images"),
    file_close_all_cmd_callback,
    PIKA_HELP_FILE_CLOSE_ALL },

  { "file-copy-location", PIKA_ICON_EDIT_COPY,
    NC_("file-action", "Copy _Image Location"), NULL, { NULL },
    NC_("file-action", "Copy image file location to clipboard"),
    file_copy_location_cmd_callback,
    PIKA_HELP_FILE_COPY_LOCATION },

  { "file-show-in-file-manager", PIKA_ICON_FILE_MANAGER,
    NC_("file-action", "Show in _File Manager"), NULL, { "<primary><alt>F", NULL },
    NC_("file-action", "Show image file location in the file manager"),
    file_show_in_file_manager_cmd_callback,
    PIKA_HELP_FILE_SHOW_IN_FILE_MANAGER },

  { "file-quit", PIKA_ICON_APPLICATION_EXIT,
    NC_("file-action", "_Quit"), NULL, { "<primary>Q", NULL },
    NC_("file-action", "Quit the Photo and Image Kooker Application"),
    file_quit_cmd_callback,
    PIKA_HELP_FILE_QUIT }
};

static const PikaEnumActionEntry file_save_actions[] =
{
  { "file-save", PIKA_ICON_DOCUMENT_SAVE,
    NC_("file-action", "_Save"), NULL, { "<primary>S", NULL },
    NC_("file-action", "Save this image"),
    PIKA_SAVE_MODE_SAVE, FALSE,
    PIKA_HELP_FILE_SAVE },

  { "file-save-as", PIKA_ICON_DOCUMENT_SAVE_AS,
    NC_("file-action", "Save _As..."), NULL, { "<primary><shift>S", NULL },
    NC_("file-action", "Save this image with a different name"),
    PIKA_SAVE_MODE_SAVE_AS, FALSE,
    PIKA_HELP_FILE_SAVE_AS },

  { "file-save-a-copy", NULL,
    NC_("file-action", "Save a Cop_y..."), NULL, { NULL },
    NC_("file-action",
        "Save a copy of this image, without affecting the source file "
        "(if any) or the current state of the image"),
    PIKA_SAVE_MODE_SAVE_A_COPY, FALSE,
    PIKA_HELP_FILE_SAVE_A_COPY },

  { "file-save-and-close", NULL,
    NC_("file-action", "Save and Close..."), NULL, { NULL },
    NC_("file-action", "Save this image and close its window"),
    PIKA_SAVE_MODE_SAVE_AND_CLOSE, FALSE,
    PIKA_HELP_FILE_SAVE },

  { "file-export", NULL,
    NC_("file-action", "E_xport..."), NULL, { "<primary>E", NULL },
    NC_("file-action", "Export the image"),
    PIKA_SAVE_MODE_EXPORT, FALSE,
    PIKA_HELP_FILE_EXPORT },

  { "file-overwrite", NULL,
    NC_("file-action", "Over_write"), NULL, { NULL },
    NC_("file-action", "Export the image back to the imported file in the import format"),
    PIKA_SAVE_MODE_OVERWRITE, FALSE,
    PIKA_HELP_FILE_OVERWRITE },

  { "file-export-as", NULL,
    NC_("file-action", "E_xport As..."), NULL, { "<primary><shift>E", NULL },
    NC_("file-action", "Export the image to various file formats such as PNG or JPEG"),
    PIKA_SAVE_MODE_EXPORT_AS, FALSE,
    PIKA_HELP_FILE_EXPORT_AS }
};

void
file_actions_setup (PikaActionGroup *group)
{
  PikaEnumActionEntry *entries;
  gint                 n_entries;
  gint                 i;

  pika_action_group_add_actions (group, "file-action",
                                 file_actions,
                                 G_N_ELEMENTS (file_actions));

  pika_action_group_add_enum_actions (group, "file-action",
                                      file_save_actions,
                                      G_N_ELEMENTS (file_save_actions),
                                      file_save_cmd_callback);

  n_entries = PIKA_GUI_CONFIG (group->pika->config)->last_opened_size;

  entries = g_new0 (PikaEnumActionEntry, n_entries);

  for (i = 0; i < n_entries; i++)
    {
      entries[i].name           = g_strdup_printf ("file-open-recent-%02d",
                                                   i + 1);
      entries[i].icon_name      = PIKA_ICON_DOCUMENT_OPEN,
      entries[i].label          = entries[i].name;
      entries[i].tooltip        = NULL;
      entries[i].value          = i;
      entries[i].value_variable = FALSE;

      if (i < 9)
        entries[i].accelerator[0] = g_strdup_printf ("<primary>%d", i + 1);
      else if (i == 9)
        entries[i].accelerator[0] = g_strdup ("<primary>0");
      else
        entries[i].accelerator[0] = NULL;
    }

  pika_action_group_add_enum_actions (group, NULL, entries, n_entries,
                                      file_open_recent_cmd_callback);

  for (i = 0; i < n_entries; i++)
    {
      pika_action_group_set_action_visible (group, entries[i].name, FALSE);

      g_free ((gchar *) entries[i].name);
      if (entries[i].accelerator[0])
        g_free ((gchar *) entries[i].accelerator[0]);
    }

  g_free (entries);

  g_signal_connect_object (group->pika->documents, "add",
                           G_CALLBACK (file_actions_last_opened_update),
                           group, 0);
  g_signal_connect_object (group->pika->documents, "remove",
                           G_CALLBACK (file_actions_last_opened_update),
                           group, 0);
  g_signal_connect_object (group->pika->documents, "reorder",
                           G_CALLBACK (file_actions_last_opened_reorder),
                           group, 0);

  file_actions_last_opened_update (group->pika->documents, NULL, group);

  /*  also listen to image adding/removal so we catch the case where
   *  the last image is closed but its display stays open.
   */
  g_signal_connect_object (group->pika->images, "add",
                           G_CALLBACK (file_actions_close_all_update),
                           group, 0);
  g_signal_connect_object (group->pika->images, "remove",
                           G_CALLBACK (file_actions_close_all_update),
                           group, 0);

  file_actions_close_all_update (group->pika->displays, NULL, group);
}

void
file_actions_update (PikaActionGroup *group,
                     gpointer         data)
{
  Pika         *pika           = action_data_get_pika (data);
  PikaImage    *image          = action_data_get_image (data);
  GList        *drawables      = NULL;
  GFile        *file           = NULL;
  GFile        *source         = NULL;
  GFile        *export         = NULL;
  gboolean      show_overwrite = FALSE;

  if (image)
    {
      drawables = pika_image_get_selected_drawables (image);

      file   = pika_image_get_file (image);
      source = pika_image_get_imported_file (image);
      export = pika_image_get_exported_file (image);
    }

  show_overwrite =
    (source &&
     pika_plug_in_manager_file_procedure_find (pika->plug_in_manager,
                                               PIKA_FILE_PROCEDURE_GROUP_EXPORT,
                                               source, NULL));

#define SET_VISIBLE(action,condition) \
        pika_action_group_set_action_visible (group, action, (condition) != 0)
#define SET_SENSITIVE(action,condition) \
        pika_action_group_set_action_sensitive (group, action, (condition) != 0, NULL)

  SET_SENSITIVE ("file-save",                 drawables);
  SET_SENSITIVE ("file-save-as",              drawables);
  SET_SENSITIVE ("file-save-a-copy",          drawables);
  SET_SENSITIVE ("file-save-and-close",       drawables);
  SET_SENSITIVE ("file-revert",               file || source);
  SET_SENSITIVE ("file-export",               drawables);
  SET_VISIBLE   ("file-export",               ! show_overwrite);
  SET_SENSITIVE ("file-overwrite",            show_overwrite);
  SET_VISIBLE   ("file-overwrite",            show_overwrite);
  SET_SENSITIVE ("file-export-as",            drawables);
  SET_SENSITIVE ("file-create-template",      image);
  SET_SENSITIVE ("file-copy-location",        file || source || export);
  SET_SENSITIVE ("file-show-in-file-manager", file || source || export);

  if (file)
    {
      pika_action_group_set_action_label (group,
                                          "file-save",
                                          C_("file-action", "_Save"));
    }
  else
    {
      pika_action_group_set_action_label (group,
                                          "file-save",
                                          C_("file-action", "_Save..."));
    }

  if (export)
    {
      gchar *label = file_actions_create_label (_("Export to %s"), export);
      pika_action_group_set_action_label (group, "file-export", label);
      g_free (label);
    }
  else if (show_overwrite)
    {
      gchar *label = file_actions_create_label (_("Over_write %s"), source);
      pika_action_group_set_action_label (group, "file-overwrite", label);
      g_free (label);
    }
  else
    {
      pika_action_group_set_action_label (group,
                                          "file-export",
                                          C_("file-action", "E_xport..."));
    }

  /*  needed for the empty display  */
  SET_SENSITIVE ("file-close-all", image);

#undef SET_SENSITIVE

  g_list_free (drawables);
}


/*  private functions  */

static void
file_actions_last_opened_update (PikaContainer   *container,
                                 PikaImagefile   *unused,
                                 PikaActionGroup *group)
{
  gint num_documents;
  gint i;
  gint n = PIKA_GUI_CONFIG (group->pika->config)->last_opened_size;

  num_documents = pika_container_get_n_children (container);

  for (i = 0; i < n; i++)
    {
      PikaAction *action;
      gchar      *name = g_strdup_printf ("file-open-recent-%02d", i + 1);

      action = pika_action_group_get_action (group, name);

      if (i < num_documents)
        {
          PikaImagefile *imagefile = (PikaImagefile *)
            pika_container_get_child_by_index (container, i);

          if (pika_action_get_viewable (action) != (PikaViewable *) imagefile)
            {
              GFile       *file;
              const gchar *name;
              gchar       *basename;
              gchar       *escaped;
              gchar       *label;

              file = pika_imagefile_get_file (imagefile);

              name     = pika_file_get_utf8_name (file);
              basename = g_path_get_basename (name);

              escaped = pika_escape_uline (basename);
              g_free (basename);
              /* TRANSLATORS: the %s will be replaced by the file name of a
               * recently opened image.
               */
              label   = g_strdup_printf (_("Open \"%s\""), escaped);

              g_object_set (action,
                            "label",       label,
                            "short-label", escaped,
                            "tooltip",     name,
                            "visible",     TRUE,
                            "viewable",    imagefile,
                            NULL);

              g_free (label);
              g_free (escaped);
            }
        }
      else
        {
          g_object_set (action,
                        "label",    name,
                        "tooltip",  NULL,
                        "visible",  FALSE,
                        "viewable", NULL,
                        NULL);
        }

      g_free (name);
    }
}

static void
file_actions_last_opened_reorder (PikaContainer   *container,
                                  PikaImagefile   *unused1,
                                  gint             unused2,
                                  PikaActionGroup *group)
{
  file_actions_last_opened_update (container, unused1, group);
}

static void
file_actions_close_all_update (PikaContainer   *images,
                               PikaObject      *unused,
                               PikaActionGroup *group)
{
  PikaContainer *container  = group->pika->displays;
  gint           n_displays = pika_container_get_n_children (container);
  gboolean       sensitive  = (n_displays > 0);

  if (n_displays == 1)
    {
      PikaDisplay *display;

      display = PIKA_DISPLAY (pika_container_get_first_child (container));

      if (! pika_display_get_image (display))
        sensitive = FALSE;
    }

  pika_action_group_set_action_sensitive (group, "file-close-all", sensitive, NULL);
}

static gchar *
file_actions_create_label (const gchar *format,
                           GFile       *file)
{
  gchar *basename         = g_path_get_basename (pika_file_get_utf8_name (file));
  gchar *escaped_basename = pika_escape_uline (basename);
  gchar *label            = g_strdup_printf (format, escaped_basename);

  g_free (escaped_basename);
  g_free (basename);

  return label;
}
