/*
 *  $Id: ptranslate.c 30047 2026-06-11 08:30:45Z yeti-dn $
 *  Copyright (C) 2024 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 <gwy.h>

#include "../preview.h"

#define RUN_MODES (GWY_RUN_IMMEDIATE | GWY_RUN_INTERACTIVE)

enum {
    RESPONSE_CENTRE = GWY_RESPONSE_USER,
};

enum {
    PARAM_X,
    PARAM_Y,
    PARAM_XPIX,
    PARAM_YPIX,
    PARAM_MOVE_TO,
    PARAM_DISPLAY,
    PARAM_UPDATE_OFFSETS,
    PARAM_NEW_IMAGE,

    BUTTON_CENTRE,
};

typedef enum {
    PREVIEW_IMAGE  = 0,
    PREVIEW_RESULT = 1,
    PREVIEW_NTYPES,
} PreviewType;

typedef enum {
    TARGET_CENTRE = 0,
    TARGET_ORIGIN = 1,
    TARGET_NTYPES,
} TargetType;

typedef struct {
    GwyParams *params;
    GwyField *field;
    GwyField *result;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table;
    GtkWidget *dataview;
    GwyVectorLayer *vlayer;
    GwySelection *selection;
    gboolean changing_selection;
} 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             selection_changed   (ModuleGUI *gui,
                                             gint i);
static void             preview             (gpointer user_data);
static void             dialog_response     (GwyDialog *dialog,
                                             gint response,
                                             ModuleGUI *gui);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Translates images in the XY plane, treating them as periodic."),
    "Yeti <yeti@gwyddion.net>",
    "1.0",
    "David Nečas (Yeti)",
    "2024",
};

GWY_MODULE_QUERY2(module_info, ptranslate)

static gboolean
module_register(void)
{
    gwy_image_func_register("periodic_translate",
                            module_main,
                            N_("/_Correct Data/_Translate Periodically..."),
                            GWY_ICON_TRANSLATE_PERIODICALLY,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Move data in XY plane, treating it as periodic"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static const GwyEnum displays[] = {
        { N_("Original _image"), PREVIEW_IMAGE,  },
        { N_("Correc_ted data"), PREVIEW_RESULT, },
    };
    static const GwyEnum targets[] = {
        { N_("Center"),          TARGET_CENTRE, },
        { N_("Top left corner"), TARGET_ORIGIN, },
    };
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, gwy_image_func_current());
    /* The relative positions we store in settings, but do not show. */
    gwy_param_def_add_double(paramdef, PARAM_X, "x", _("_X"), 0.0, 1.0, 0.5);
    gwy_param_def_add_double(paramdef, PARAM_Y, "y", _("_Y"), 0.0, 1.0, 0.5);
    /* We show image-scaled positions the GUI. */
    gwy_param_def_add_int(paramdef, PARAM_XPIX, NULL, _("_X"), 0, G_MAXINT, 0);
    gwy_param_def_add_int(paramdef, PARAM_YPIX, NULL, _("_Y"), 0, G_MAXINT, 0);

    gwy_param_def_add_gwyenum(paramdef, PARAM_MOVE_TO, "move-to", _("_Move selected point to"),
                              targets, G_N_ELEMENTS(targets), TARGET_CENTRE);
    gwy_param_def_add_gwyenum(paramdef, PARAM_DISPLAY, "display", C_("verb", "Display"),
                              displays, G_N_ELEMENTS(displays), PREVIEW_IMAGE);
    gwy_param_def_add_boolean(paramdef, PARAM_UPDATE_OFFSETS, "update-offsets", _("_Update coordinate offsets"), FALSE);
    gwy_param_def_add_boolean(paramdef, PARAM_NEW_IMAGE, "new-image", _("Create new image"), FALSE);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    ModuleArgs args;
    GQuark dquark;
    gint id, newid;

    g_return_if_fail(mode & RUN_MODES);
    gwy_data_browser_get_current(GWY_APP_FIELD, &args.field,
                                 GWY_APP_FIELD_KEY, &dquark,
                                 GWY_APP_FIELD_ID, &id,
                                 0);
    g_return_if_fail(args.field && dquark);

    args.result = gwy_field_copy(args.field);
    args.params = gwy_params_new_from_settings(define_module_params());
    /* This can set the values one too large (xres insteas of xres-1), but we restrict the range later. */
    gwy_params_set_int(args.params, PARAM_XPIX,
                       GWY_ROUND(gwy_field_get_xres(args.field)*gwy_params_get_double(args.params, PARAM_X)));
    gwy_params_set_int(args.params, PARAM_YPIX,
                       GWY_ROUND(gwy_field_get_yres(args.field)*gwy_params_get_double(args.params, PARAM_Y)));

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

    if (gwy_params_get_boolean(args.params, PARAM_NEW_IMAGE)) {
        newid = gwy_file_add_image(data, args.result);
        gwy_file_set_visible(data, GWY_FILE_IMAGE, newid, TRUE);
        gwy_file_set_title(data, GWY_FILE_IMAGE, newid, _("Translated"), TRUE);
        gwy_file_sync_items(data, GWY_FILE_IMAGE, id,
                            data, GWY_FILE_IMAGE, newid,
                            GWY_FILE_ITEM_PALETTE | GWY_FILE_ITEM_REAL_SQUARE | GWY_FILE_ITEM_RANGE, FALSE);
        gwy_log_add(data, GWY_FILE_IMAGE, id, newid);
    }
    else {
        gwy_app_undo_qcheckpointv(GWY_DICT(data), 1, &dquark);
        gwy_field_assign(args.field, args.result);
        gwy_field_data_changed(args.field);
        gwy_log_add(data, GWY_FILE_IMAGE, id, id);
    }

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

static GwyDialogOutcome
run_gui(ModuleArgs *args, GwyFile *data, gint id)
{
    GtkWidget *hbox;
    GwyDialogOutcome outcome;
    GwyParamTable *table;
    GwyDialog *dialog;
    ModuleGUI gui;

    gwy_clear1(gui);
    gui.args = args;

    gui.dialog = gwy_dialog_new(_("Translate Periodically"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_RESET, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    gui.dataview = gwy_create_preview(args->field, NULL, PREVIEW_SIZE);
    gwy_setup_data_view(GWY_DATA_VIEW(gui.dataview), data, GWY_FILE_IMAGE, id,
                        GWY_FILE_ITEM_PALETTE | GWY_FILE_ITEM_REAL_SQUARE | GWY_FILE_ITEM_RANGE);
    gui.selection = gwy_create_preview_vector_layer(GWY_DATA_VIEW(gui.dataview), GWY_TYPE_LAYER_POINT, 1, TRUE);
    gui.vlayer = g_object_ref(gwy_data_view_get_interactive_layer(GWY_DATA_VIEW(gui.dataview)));
    hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(gui.dataview), FALSE);

    table = gui.table = gwy_param_table_new(args->params);

    gwy_param_table_append_header(table, -1, _("Translation"));
    gwy_param_table_append_slider(table, PARAM_XPIX);
    gwy_param_table_slider_restrict_range(table, PARAM_XPIX, 0, gwy_field_get_xres(args->field)-1);
    gwy_param_table_set_no_reset(table, PARAM_XPIX, TRUE);
    gwy_param_table_set_unitstr(table, PARAM_XPIX, _("px"));
    gwy_param_table_slider_add_alt(table, PARAM_XPIX);
    gwy_param_table_alt_set_field_pixel_x(table, PARAM_XPIX, args->field);

    gwy_param_table_append_slider(table, PARAM_YPIX);
    gwy_param_table_slider_restrict_range(table, PARAM_YPIX, 0, gwy_field_get_yres(args->field)-1);
    gwy_param_table_set_no_reset(table, PARAM_YPIX, TRUE);
    gwy_param_table_set_unitstr(table, PARAM_YPIX, _("px"));
    gwy_param_table_slider_add_alt(table, PARAM_YPIX);
    gwy_param_table_alt_set_field_pixel_y(table, PARAM_YPIX, args->field);

    gwy_param_table_append_button(table, BUTTON_CENTRE, -1, RESPONSE_CENTRE, _("_Select Center"));

    gwy_param_table_append_separator(table);
    gwy_param_table_append_radio(table, PARAM_MOVE_TO);

    gwy_param_table_append_header(table, -1, _("Options"));
    gwy_param_table_append_checkbox(table, PARAM_UPDATE_OFFSETS);
    gwy_param_table_append_checkbox(table, PARAM_NEW_IMAGE);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_radio(table, PARAM_DISPLAY);

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

    g_signal_connect_swapped(table, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect(dialog, "response", G_CALLBACK(dialog_response), &gui);
    g_signal_connect_swapped(gui.selection, "changed", G_CALLBACK(selection_changed), &gui);
    gwy_dialog_set_preview_func(dialog, GWY_PREVIEW_IMMEDIATE, preview, &gui, NULL);

    outcome = gwy_dialog_run(dialog);

    g_object_unref(gui.vlayer);

    return outcome;
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    ModuleArgs *args = gui->args;
    GwyParams *params = args->params;

    if (id < 0 || id == PARAM_DISPLAY) {
        GwyDataView *dataview = GWY_DATA_VIEW(gui->dataview);
        PreviewType ptype = gwy_params_get_enum(params, PARAM_DISPLAY);

        if (ptype == PREVIEW_RESULT) {
            gwy_data_view_set_field(dataview, args->result);
            gwy_data_view_set_interactive_layer(dataview, NULL);
        }
        else {
            gwy_data_view_set_field(dataview, args->field);
            gwy_data_view_set_interactive_layer(dataview, gui->vlayer);
        }
    }

    if (id < 0 || id == PARAM_XPIX) {
        gdouble x = gwy_params_get_int(params, PARAM_XPIX);
        gwy_params_set_double(params, PARAM_X, x/gwy_field_get_xres(args->field));
    }
    if (id < 0 || id == PARAM_YPIX) {
        gdouble y = gwy_params_get_int(params, PARAM_YPIX);
        gwy_params_set_double(params, PARAM_Y, y/gwy_field_get_yres(args->field));
    }
    if (!gui->changing_selection && (id < 0 || id == PARAM_XPIX || id == PARAM_YPIX)) {
        gdouble xy[2];
        xy[0] = gwy_field_jtor(args->field, gwy_params_get_int(params, PARAM_XPIX));
        xy[1] = gwy_field_itor(args->field, gwy_params_get_int(params, PARAM_YPIX));
        gui->changing_selection = TRUE;
        gwy_selection_set_object(gui->selection, 0, xy);
        gui->changing_selection = FALSE;
    }

    /* XXX: Changing UPDATE_OFFSETS does not actually change how the preview looks, but we would get the wrong output
     * if the dialog thought the computed result is still valid. */
    if (id != PARAM_NEW_IMAGE)
        gwy_dialog_invalidate(GWY_DIALOG(gui->dialog));
}

static void
selection_changed(ModuleGUI *gui, G_GNUC_UNUSED gint i)
{
    GwyField *field = gui->args->field;
    gdouble xy[2];
    gdouble col, row;

    if (gui->changing_selection || !gwy_selection_get_object(gui->selection, 0, xy))
        return;

    gui->changing_selection = TRUE;
    col = gwy_field_rtoj(field, xy[0]);
    row = gwy_field_rtoi(field, xy[1]);
    gwy_param_table_set_int(gui->table, PARAM_XPIX, CLAMP(GWY_ROUND(col), 0, field->xres-1));
    gwy_param_table_set_int(gui->table, PARAM_YPIX, CLAMP(GWY_ROUND(row), 0, field->yres-1));
    gui->changing_selection = FALSE;
}

static void
preview(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;
    ModuleArgs *args = gui->args;

    execute(args);
    gwy_field_data_changed(args->result);
    gwy_dialog_have_result(GWY_DIALOG(gui->dialog));
}

static void
dialog_response(G_GNUC_UNUSED GwyDialog *dialog, gint response, ModuleGUI *gui)
{
    if (response == RESPONSE_CENTRE || response == GWY_RESPONSE_RESET) {
        gwy_param_table_set_int(gui->table, PARAM_XPIX, gwy_field_get_xres(gui->args->field)/2);
        gwy_param_table_set_int(gui->table, PARAM_YPIX, gwy_field_get_yres(gui->args->field)/2);
    }
}

static gdouble
update_offset(gdouble off, gint res, gdouble real, gint pxshift)
{
    gdouble d = real/res;

    off = fmod(off + d*pxshift, real);
    if (off < 0.5*real)
        off += real;
    if (off > 0.5*real)
        off -= real;

    return off;
}

/* @xshift and @yshift are move-by-this-amount parameters. Alternatively, they can be interpreted as to move the pixel
 * at (-@xshift,-@yshift) to the top left corner (0,0). */
static void
gwy_field_translate_periodically(GwyField *field,
                                 gint xshift, gint yshift,
                                 gboolean update_offsets)
{
    GwyField *tmp;
    gint xres, yres, xcompl, ycompl;

    g_return_if_fail(GWY_IS_FIELD(field));

    xres = field->xres;
    yres = field->yres;
    if (!xshift && !yshift)
        return;

    /* Make (xhsift, yshift) coordinates of the pixel which will become the new origin and fold them to the field
     * pixel range. */
    xshift = (-xshift % xres + xres) % xres;
    yshift = (-yshift % yres + yres) % yres;
    xcompl = xres - xshift;
    ycompl = yres - yshift;

    tmp = gwy_field_copy(field);
    gwy_debug("xshift = %d, yshift = %d", xshift, yshift);
    gwy_field_area_copy(tmp, field, 0, 0, xshift, yshift, xcompl, ycompl);
    gwy_field_area_copy(tmp, field, xshift, yshift, xres - xshift, yres - yshift, 0, 0);
    gwy_field_area_copy(tmp, field, 0, yshift, xshift, ycompl, xcompl, 0);
    gwy_field_area_copy(tmp, field, xshift, 0, xcompl, yshift, 0, ycompl);
    g_object_unref(tmp);

    if (update_offsets) {
        gdouble xreal = gwy_field_get_xreal(field), yreal = gwy_field_get_yreal(field);
        gdouble xoff = gwy_field_get_xoffset(field), yoff = gwy_field_get_yoffset(field);

        gwy_field_set_xoffset(field, update_offset(xoff, xres, xreal, xshift));
        gwy_field_set_yoffset(field, update_offset(yoff, yres, yreal, yshift));
    }
}

static void
execute(ModuleArgs *args)
{
    GwyField *field = args->field, *result = args->result;
    gint xres = gwy_field_get_xres(field), yres = gwy_field_get_yres(field);
    gint xsel = gwy_params_get_int(args->params, PARAM_XPIX);
    gint ysel = gwy_params_get_int(args->params, PARAM_YPIX);
    gboolean update_offsets = gwy_params_get_boolean(args->params, PARAM_UPDATE_OFFSETS);
    TargetType target = gwy_params_get_enum(args->params, PARAM_MOVE_TO);
    gint xtarget = (target == TARGET_ORIGIN ? 0 : xres/2);
    gint ytarget = (target == TARGET_ORIGIN ? 0 : yres/2);

    gwy_field_assign(result, field);
    gwy_field_translate_periodically(result, xtarget - xsel, ytarget - ysel, update_offsets);
}

/* 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 : */
