/*
 *  $Id: volume_addframe.c 30047 2026-06-11 08:30:45Z yeti-dn $
 *  Copyright (C) 2015-2021 David Necas (Yeti).
 *  E-mail: yeti@gwyddion.net.
 *
 *  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 2 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, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <glib/gi18n-lib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gwy.h>

#define RUN_MODES (GWY_RUN_INTERACTIVE)

enum {
    PREVIEW_SIZE = 360,
    RESPONSE_BEFORE = GWY_RESPONSE_USER,
    RESPONSE_REPLACE,
    RESPONSE_AFTER,
};

enum {
    PARAM_ADD_IMAGE,
    PARAM_Z,
    BUTTON_BEFORE,
    BUTTON_REPLACE,
    BUTTON_AFTER
};

typedef struct {
    GwyParams *params;
    GwyBrick *brick;
    GwyBrick *result;
    gboolean after;
    gboolean replace;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GtkWidget *dataview;
    GwyParamTable *table_options;
} ModuleGUI;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static void             execute             (ModuleArgs *args);
static GwyDialogOutcome run_gui             (ModuleArgs *args,
                                             GwyFile *data,
                                             gint id);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);
static void             dialog_response     (GwyDialog *dialog,
                                             gint response,
                                             ModuleGUI *gui);
static void             addit               (gpointer user_data);
static void             update_image        (ModuleGUI *gui,
                                             gint z);
static gboolean         add_image_filter    (GwyFile *data,
                                             gint id,
                                             gpointer user_data);

static void                  sanitise_params          (ModuleArgs *args);


static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Add one frame to volume data stack"),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "1.1",
    "Petr Klapetek & David Nečas (Yeti)",
    "2023",
};

GWY_MODULE_QUERY2(module_info, volume_addframe)

static gboolean
module_register(void)
{
    gwy_volume_func_register("volume_addframe",
                             module_main,
                             N_("/_Basic Operations/I_nsert XY Plane..."),
                             NULL,
                             RUN_MODES,
                             GWY_MENU_FLAG_VOLUME,
                             N_("Insert single XY plane to some level."));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, gwy_volume_func_current());
    gwy_param_def_add_image_id(paramdef, PARAM_ADD_IMAGE, "add_image", _("Data to insert"));
    gwy_param_def_add_int(paramdef, PARAM_Z, "z", "Preview level", 0, G_MAXINT, 0);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    ModuleArgs args;
    GwyBrick *brick = NULL;
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    gint oldid, newid;

    g_return_if_fail(mode & RUN_MODES);

    gwy_data_browser_get_current(GWY_APP_BRICK, &brick,
                                 GWY_APP_BRICK_ID, &oldid,
                                 0);
    g_return_if_fail(GWY_IS_BRICK(brick));
    args.result = NULL;
    args.brick = brick;
    args.after = FALSE;
    args.replace = FALSE;
    args.params = gwy_params_new_from_settings(define_module_params());
    sanitise_params(&args);

    if (mode == GWY_RUN_INTERACTIVE) {
        outcome = run_gui(&args, data, oldid);
        gwy_params_save_to_settings(args.params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    if (outcome != GWY_DIALOG_HAVE_RESULT)
        execute(&args);

    newid = gwy_file_add_volume(data, args.result, NULL);

    gwy_file_set_visible(data, GWY_FILE_VOLUME, newid, TRUE);

    gwy_file_set_title(data, GWY_FILE_VOLUME, newid, _("Frame added"), TRUE);
    gwy_file_sync_items(data, GWY_FILE_VOLUME, oldid,
                        data, GWY_FILE_VOLUME, newid,
                        GWY_FILE_ITEM_PALETTE, FALSE);

    gwy_log_add(data, GWY_FILE_VOLUME, -1, newid);

end:
    g_object_unref(args.params);
    g_object_unref(args.result);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args, GwyFile *data, gint id)
{
    GtkWidget *hbox, *dataview;
    GwyParamTable *table;
    GwyDialog *dialog;
    ModuleGUI gui;
    GwyBrick *brick = args->brick;
    GwyField *field = gwy_brick_new_field_like_xy_plane(brick, TRUE);

    gwy_clear1(gui);
    gui.args = args;

    args->result = gwy_brick_copy(brick);

    gui.dialog = gwy_dialog_new(_("Add XY Plane"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_RESET, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    dataview = gui.dataview = gwy_create_preview(field, NULL, PREVIEW_SIZE);
    gwy_setup_data_view(GWY_DATA_VIEW(dataview), data, GWY_FILE_VOLUME, id, GWY_FILE_ITEM_PALETTE);
    hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(dataview), FALSE);

    table = gui.table_options = gwy_param_table_new(args->params);
    gwy_param_table_append_slider(table, PARAM_Z);
    gwy_param_table_slider_restrict_range(table, PARAM_Z, 0, gwy_brick_get_zres(brick)-1);
    gwy_param_table_append_image_id(table, PARAM_ADD_IMAGE);
    gwy_param_table_data_id_set_filter(table, PARAM_ADD_IMAGE, add_image_filter, args->brick, NULL);

    gwy_param_table_append_button(table, BUTTON_BEFORE, -1, RESPONSE_BEFORE, _("Insert _Before Current Level"));
    gwy_param_table_append_button(table, BUTTON_REPLACE, -1, RESPONSE_REPLACE, _("_Replace Current Level"));
    gwy_param_table_append_button(table, BUTTON_AFTER, -1, RESPONSE_AFTER, _("Insert _After Current Level"));

    gtk_box_pack_start(GTK_BOX(hbox), gwy_param_table_widget(table), TRUE, TRUE, 0);

    g_signal_connect_swapped(gui.table_options, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_after(dialog, "response", G_CALLBACK(dialog_response), &gui);

    return gwy_dialog_run(dialog);
}

static void
param_changed(ModuleGUI *gui, G_GNUC_UNUSED gint id)
{
    gint z = gwy_params_get_int(gui->args->params, PARAM_Z);
    update_image(gui, z);
}

static void
dialog_response(G_GNUC_UNUSED GwyDialog *dialog, gint response, ModuleGUI *gui)
{
    gint z = gwy_params_get_int(gui->args->params, PARAM_Z);

    if (response == GWY_RESPONSE_RESET) {
        g_object_unref(gui->args->result);
        gui->args->result = gwy_brick_copy(gui->args->brick);
        gwy_param_table_slider_restrict_range(gui->table_options, PARAM_Z, 0,
                                              gwy_brick_get_zres(gui->args->result) - 1);
        update_image(gui, z);
    }
    else if (response == RESPONSE_BEFORE) {
        gui->args->after = FALSE;
        gui->args->replace = FALSE;
        addit(gui);
    }
    else if (response == RESPONSE_REPLACE) {
        gui->args->after = FALSE;
        gui->args->replace = TRUE;
        addit(gui);
    }
    else if (response == RESPONSE_AFTER) {
        gui->args->after = TRUE;
        gui->args->replace = FALSE;
        addit(gui);
    }
}

static void
update_image(ModuleGUI *gui, gint z)
{
    GwyBrick *brick = gui->args->result;
    gint zres = gwy_brick_get_zres(brick);
    GwyField *field = gwy_data_view_get_field(GWY_DATA_VIEW(gui->dataview));
    gwy_brick_extract_xy_plane(brick, field, CLAMP(z, 0, zres-1));
    gwy_field_data_changed(field);
}

static void
addit(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;
    ModuleArgs *args = gui->args;
    GwyBrick *brick = args->result;
    gint zres = gwy_brick_get_zres(brick);
    gint z = CLAMP(gwy_params_get_int(args->params, PARAM_Z), 0, zres-1);

    execute(args);
    gwy_param_table_slider_restrict_range(gui->table_options, PARAM_Z, 0, zres-1);
    update_image(gui, z);
    gwy_dialog_have_result(GWY_DIALOG(gui->dialog));
}

static void
execute(ModuleArgs *args)
{
    GwyParams *params = args->params;
    gint k, m;
    GwyBrick *original = args->result;
    GwyBrick *newbrick;
    GwyField *dfield, *addfield = gwy_params_get_image(args->params, PARAM_ADD_IMAGE);
    gint level = gwy_params_get_int(params, PARAM_Z);
    gint xres = gwy_brick_get_xres(original);
    gint yres = gwy_brick_get_yres(original);
    gint zres = gwy_brick_get_zres(original);
    gdouble xreal = gwy_brick_get_xreal(original);
    gdouble yreal = gwy_brick_get_yreal(original);
    gdouble zreal = gwy_brick_get_zreal(original);
    gint newzres;

    if (args->replace) {
       gwy_brick_set_xy_plane(args->result, addfield, level);
    }
    else {
        newzres = zres + 1;
        newbrick = gwy_brick_new(xres, yres, newzres,
                                 xreal, yreal, newzres*zreal/zres,
                                 FALSE);

        gwy_brick_copy_units(original, newbrick);

        dfield = gwy_field_new(xres, yres, xreal, yreal, FALSE);
        if (args->after)
            level++;

        m = 0;
        for (k = 0; k < newzres; k++) {
            if (k == level)
                gwy_brick_set_xy_plane(newbrick, addfield, k);
            else {
               gwy_brick_extract_xy_plane(original, dfield, m++);
               gwy_brick_set_xy_plane(newbrick, dfield, k);
            }
        }
        g_object_unref(original);
        args->result = newbrick;
        g_object_unref(dfield);
    }
}

static gboolean
add_image_filter(GwyFile *data, gint id, gpointer user_data)
{
    GwyBrick *brick = (GwyBrick*)user_data;
    GwyField *field;

    if (!(field = gwy_file_get_image(data, id)))
        return FALSE;
    return !gwy_field_is_incompatible_with_brick_xy(field, brick,
                                                    GWY_DATA_MISMATCH_RES
                                                    | GWY_DATA_MISMATCH_REAL
                                                    | GWY_DATA_MISMATCH_LATERAL
                                                    | GWY_DATA_MISMATCH_VALUE);
}

static void
sanitise_one_param(GwyParams *params, gint id, gint min, gint max, gint defval)
{
    gint v;

    v = gwy_params_get_int(params, id);
    if (v >= min && v <= max) {
        gwy_debug("param #%d is %d, i.e. within range [%d..%d]", id, v, min, max);
        return;
    }
    gwy_debug("param #%d is %d, setting it to the default %d", id, v, defval);
    gwy_params_set_int(params, id, defval);
}

static void
sanitise_params(ModuleArgs *args)
{
    GwyParams *params = args->params;
    sanitise_one_param(params, PARAM_Z, 0, gwy_brick_get_zres(args->brick), 0);
}

/* vim: set cin columns=120 tw=118 et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */
