/* 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) 2009 Martin Nordholts
 *
 * 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 <stdlib.h>

#include <gegl.h>
#include <gtk/gtk.h>

#include "gui/gui-types.h"

#include "gui/gui.h"

#include "actions/actions.h"

#include "menus/menus.h"

#include "widgets/pikasessioninfo.h"

#include "config/pikageglconfig.h"

#include "core/pika.h"
#include "core/pika-contexts.h"

#include "gegl/pika-gegl.h"

#include "pika-log.h"
#include "pikacoreapp.h"

#include "pika-app-test-utils.h"
#include "tests.h"

#ifdef GDK_WINDOWING_QUARTZ
#include <Cocoa/Cocoa.h>
#endif


static void
pika_status_func_dummy (const gchar *text1,
                        const gchar *text2,
                        gdouble      percentage)
{
}

/**
 * pika_init_for_testing:
 *
 * Initialize the PIKA object system for unit testing. This is a
 * selected subset of the initialization happening in app_run().
 **/
Pika *
pika_init_for_testing (void)
{
  Pika *pika;

  pika_log_init ();
  gegl_init (NULL, NULL);

  pika = pika_new ("Unit Tested PIKA", NULL, NULL, FALSE, TRUE, TRUE, TRUE,
                   FALSE, FALSE, TRUE, FALSE, FALSE,
                   PIKA_STACK_TRACE_QUERY, PIKA_PDB_COMPAT_OFF);

  pika_load_config (pika, NULL, NULL);

  pika_gegl_init (pika);
  pika_initialize (pika, pika_status_func_dummy);
  pika_restore (pika, pika_status_func_dummy, NULL);

  return pika;
}


#ifndef PIKA_CONSOLE_COMPILATION

static void
pika_init_icon_theme_for_testing (void)
{
  gchar       *icon_root;

  icon_root = g_test_build_filename (G_TEST_BUILT, "pika-test-icon-theme", NULL);
  gtk_icon_theme_prepend_search_path (gtk_icon_theme_get_default (),
                                      icon_root);
  g_free (icon_root);
  return;
}

#ifdef GDK_WINDOWING_QUARTZ
static gboolean
pika_osx_focus_window (gpointer user_data)
{
  [NSApp activateIgnoringOtherApps:YES];
  return FALSE;
}
#endif

static void
pika_test_app_activate_callback (PikaCoreApp *app,
                                 gpointer     user_data)
{
  Pika *pika = NULL;

  g_return_if_fail (PIKA_IS_CORE_APP (app));

  pika = pika_core_app_get_pika (app);

  pika_core_app_set_exit_status (app, EXIT_SUCCESS);

  gui_init (pika, TRUE, NULL, g_getenv ("PIKA_TESTING_ABS_TOP_SRCDIR"));
  pika_init_icon_theme_for_testing ();
  pika_initialize (pika, pika_status_func_dummy);
  pika_restore (pika, pika_status_func_dummy, NULL);
#ifdef GDK_WINDOWING_QUARTZ
  g_idle_add (pika_osx_focus_window, NULL);
#endif
  pika->initialized = TRUE;
  pika_core_app_set_exit_status (app, g_test_run ());

  /* Don't write files to the source dir */
  pika_test_utils_set_pika3_directory ("PIKA_TESTING_ABS_TOP_BUILDDIR",
                                       "app/tests/pikadir-output");

  pika_exit (pika, TRUE);
}

static Pika *
pika_init_for_gui_testing_internal (gboolean  show_gui,
                                    GFile    *pikarc)
{
  Pika *pika;

  /* Load configuration from the source dir */
  pika_test_utils_set_pika3_directory ("PIKA_TESTING_ABS_TOP_SRCDIR",
                                       "app/tests/pikadir");

#if defined (G_OS_WIN32)
  /* g_test_init() sets warnings always fatal, which is a usually a good
     testing default. Nevertheless the Windows platform may have a few
     quirks generating warnings, yet we want to finish tests. So we
     allow some relaxed rules on this platform. */

  GLogLevelFlags fatal_mask;

  fatal_mask = (GLogLevelFlags) (G_LOG_FATAL_MASK | G_LOG_LEVEL_CRITICAL);
  g_log_set_always_fatal (fatal_mask);
#endif

  /* from main() */
  pika_log_init ();
  gegl_init (NULL, NULL);

  /* Introduce an error margin for positions written to sessionrc */
  pika_session_info_set_position_accuracy (5);

  /* from app_run() */
  pika = pika_new ("Unit Tested PIKA", NULL, NULL, FALSE, TRUE, TRUE, !show_gui,
                   FALSE, FALSE, TRUE, FALSE, FALSE,
                   PIKA_STACK_TRACE_QUERY, PIKA_PDB_COMPAT_OFF);
  pika->app = pika_app_new (pika, TRUE, FALSE, FALSE, NULL, NULL, NULL);

  pika_set_show_gui (pika, show_gui);
  pika_load_config (pika, pikarc, NULL);
  pika_gegl_init (pika);

  g_signal_connect (pika->app, "activate",
                    G_CALLBACK (pika_test_app_activate_callback),
                    NULL);
  return pika;
}

/**
 * pika_init_for_gui_testing:
 * @show_gui:
 *
 * Initializes a #Pika instance for use in test cases that rely on GUI
 * code to be initialized.
 *
 * Returns: The #Pika instance.
 **/
Pika *
pika_init_for_gui_testing (gboolean show_gui)
{
  return pika_init_for_gui_testing_internal (show_gui, NULL);
}

/**
 * pika_init_for_gui_testing:
 * @show_gui:
 * @pikarc:
 *
 * Like pika_init_for_gui_testing(), but also allows a custom pikarc
 * filename to be specified.
 *
 * Returns: The #Pika instance.
 **/
Pika *
pika_init_for_gui_testing_with_rc (gboolean  show_gui,
                                   GFile    *pikarc)
{
  return pika_init_for_gui_testing_internal (show_gui, pikarc);
}

#endif /* PIKA_CONSOLE_COMPILATION */

static gboolean
pika_tests_quit_mainloop (GMainLoop *loop)
{
  g_main_loop_quit (loop);

  return FALSE;
}

/**
 * pika_test_run_temp_mainloop:
 * @running_time: The time to run the main loop.
 *
 * Helper function for tests that wants to run a main loop for a
 * while. Useful when you want PIKA's state to settle before doing
 * tests.
 **/
void
pika_test_run_temp_mainloop (guint32 running_time)
{
  GMainLoop *loop;
  loop = g_main_loop_new (NULL, FALSE);

  g_timeout_add (running_time,
                 (GSourceFunc) pika_tests_quit_mainloop,
                 loop);

  g_main_loop_run (loop);

  g_main_loop_unref (loop);
}

/**
 * pika_test_run_mainloop_until_idle:
 *
 * Creates and runs a main loop until it is idle, i.e. has no more
 * work to do.
 **/
void
pika_test_run_mainloop_until_idle (void)
{
  GMainLoop *loop = g_main_loop_new (NULL, FALSE);

  g_idle_add ((GSourceFunc) pika_tests_quit_mainloop, loop);

  g_main_loop_run (loop);

  g_main_loop_unref (loop);
}

/**
 * pika_test_bail_if_no_display:
 * @void:
 *
 * If no DISPLAY is set, call exit(EXIT_SUCCESS). There is no use in
 * having UI tests failing in DISPLAY-less environments.
 **/
void
pika_test_bail_if_no_display (void)
{
  if (! g_getenv ("DISPLAY"))
    {
      g_message ("No DISPLAY set, not running UI tests\n");
      exit (EXIT_SUCCESS);
    }
}
