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

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

#include "core-types.h"

#include "pika.h"
#include "pika-templates.h"
#include "pikalist.h"
#include "pikatemplate.h"


/* functions to load and save the pika templates files */

void
pika_templates_load (Pika *pika)
{
  GFile  *file;
  GError *error = NULL;

  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (PIKA_IS_LIST (pika->templates));

  file = pika_directory_file ("templaterc", NULL);

  if (pika->be_verbose)
    g_print ("Parsing '%s'\n", pika_file_get_utf8_name (file));

  if (! pika_config_deserialize_file (PIKA_CONFIG (pika->templates),
                                      file, NULL, &error))
    {
      if (error->code == PIKA_CONFIG_ERROR_OPEN_ENOENT)
        {
          g_clear_error (&error);
          g_object_unref (file);

          if (g_getenv ("PIKA_TESTING_ABS_TOP_SRCDIR"))
            {
              gchar *path;
              path = g_build_filename (g_getenv ("PIKA_TESTING_ABS_TOP_SRCDIR"),
                                       "etc", "templaterc", NULL);
              file = g_file_new_for_path (path);
              g_free (path);
            }
          else
            {
              file = pika_sysconf_directory_file ("templaterc", NULL);
            }

          if (! pika_config_deserialize_file (PIKA_CONFIG (pika->templates),
                                              file, NULL, &error))
            {
              pika_message_literal (pika, NULL, PIKA_MESSAGE_ERROR,
                                    error->message);
            }
        }
      else
        {
          pika_message_literal (pika, NULL, PIKA_MESSAGE_ERROR, error->message);
        }

      g_clear_error (&error);
    }

  pika_list_reverse (PIKA_LIST (pika->templates));

  g_object_unref (file);
}

void
pika_templates_save (Pika *pika)
{
  const gchar *header =
    "PIKA templaterc\n"
    "\n"
    "This file will be entirely rewritten each time you exit.";
  const gchar *footer =
    "end of templaterc";

  GFile  *file;
  GError *error = NULL;

  g_return_if_fail (PIKA_IS_PIKA (pika));
  g_return_if_fail (PIKA_IS_LIST (pika->templates));

  file = pika_directory_file ("templaterc", NULL);

  if (pika->be_verbose)
    g_print ("Writing '%s'\n", pika_file_get_utf8_name (file));

  if (! pika_config_serialize_to_file (PIKA_CONFIG (pika->templates),
                                       file,
                                       header, footer, NULL,
                                       &error))
    {
      pika_message_literal (pika, NULL, PIKA_MESSAGE_ERROR, error->message);
      g_error_free (error);
    }

  g_object_unref (file);
}


/*  just like pika_list_get_child_by_name() but matches case-insensitive
 *  and dpi/ppi-insensitive
 */
static PikaObject *
pika_templates_migrate_get_child_by_name (PikaContainer *container,
                                          const gchar   *name)
{
  PikaList   *list   = PIKA_LIST (container);
  PikaObject *retval = NULL;
  GList      *glist;

  for (glist = list->queue->head; glist; glist = g_list_next (glist))
    {
      PikaObject *object = glist->data;
      gchar      *str1   = g_ascii_strdown (pika_object_get_name (object), -1);
      gchar      *str2   = g_ascii_strdown (name, -1);

      if (! strcmp (str1, str2))
        {
          retval = object;
        }
      else
        {
          gchar *dpi = strstr (str1, "dpi");

          if (dpi)
            {
              memcpy (dpi, "ppi", 3);

              g_print ("replaced: %s\n", str1);

              if (! strcmp (str1, str2))
                retval = object;
            }
        }

      g_free (str1);
      g_free (str2);
    }

  return retval;
}

/**
 * pika_templates_migrate:
 * @olddir: the old user directory
 *
 * Migrating the templaterc from PIKA 2.0 to PIKA 2.2 needs this special
 * hack since we changed the way that units are handled. This function
 * merges the user's templaterc with the systemwide templaterc. The goal
 * is to replace the unit for a couple of default templates with "pixels".
 **/
void
pika_templates_migrate (const gchar *olddir)
{
  PikaContainer *templates = pika_list_new (PIKA_TYPE_TEMPLATE, TRUE);
  GFile         *file      = pika_directory_file ("templaterc", NULL);

  if (pika_config_deserialize_file (PIKA_CONFIG (templates), file,
                                    NULL, NULL))
    {
      GFile *sysconf_file;

      sysconf_file = pika_sysconf_directory_file ("templaterc", NULL);

      if (olddir && (strstr (olddir, "2.0") || strstr (olddir, "2.2")))
        {
          /* We changed the spelling of a couple of template names:
           *
           * - from upper to lower case between 2.0 and 2.2
           * - from "dpi" to "ppi" between 2.2 and 2.4
           */
          PikaContainerClass *class = PIKA_CONTAINER_GET_CLASS (templates);
          gpointer            func  = class->get_child_by_name;

          class->get_child_by_name = pika_templates_migrate_get_child_by_name;

          pika_config_deserialize_file (PIKA_CONFIG (templates),
                                        sysconf_file, NULL, NULL);

          class->get_child_by_name = func;
        }
      else
        {
          pika_config_deserialize_file (PIKA_CONFIG (templates),
                                        sysconf_file, NULL, NULL);
        }

      g_object_unref (sysconf_file);

      pika_list_reverse (PIKA_LIST (templates));

      pika_config_serialize_to_file (PIKA_CONFIG (templates), file,
                                     NULL, NULL, NULL, NULL);
    }

  g_object_unref (file);
}
