/*
 *  $Id: xyz_fft.c 30047 2026-06-11 08:30:45Z yeti-dn $
 *  Copyright (C) 2016-2026 David Necas (Yeti).
 *
 *  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,
    MAXN = 10000
};

enum {
    PARAM_DATA,
    PARAM_SUPPRESS,
    PARAM_OUTPUT,
    PARAM_ZOOM,
    PARAM_LOGSCALE,
    PARAM_AXIS,
};

typedef enum {
    SUPPRESS_NULL         = 0,
    SUPPRESS_NEIGBOURHOOD = 1
} GwyFFTFilt1DSuppressType;

typedef enum {
    OUTPUT_MARKED   = 0,
    OUTPUT_UNMARKED = 1
} GwyFFTFilt1DOutputType;

typedef enum {
    FFT_X      = 0,
    FFT_Y      = 1,
    FFT_VALUES = 2,
} FFTWhat;

typedef enum {
    ZOOM_100 = 0,
    ZOOM_20  = 1,
    ZOOM_1   = 2,
} FFTZoomType;

typedef struct {
    GwyParams *params;
    GwyScatter *scatter;
    GwyScatter *result;
    GwySelection *graph_selection;
    GwyLine *fftinput;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table_options;
    GwyParamTable *table_axis;
    GwyParamTable *table_view;
    GwyGraphModel *gmodel;
    GwyField *field;
    GwyLine *spectrum;
} ModuleGUI;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static gboolean         execute             (ModuleArgs *args,
                                             GtkWindow *wait_window);
static GwyDialogOutcome run_gui             (ModuleArgs *args,
                                             GwyFile *data,
                                             gint id);
static void             preview             (gpointer user_data);
static void             dialog_response     (GwyDialog *dialog,
                                             gint response,
                                             ModuleGUI *gui);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);
static void             calculate_fft_curve (ModuleGUI *gui);
static void             update_fft_curve    (ModuleGUI *gui);
static void             copy_data_to_line   (GwyScatter *scatter,
                                             FFTWhat what,
                                             gint idata,
                                             GwyLine *line);
static void             calculate_weights   (GwyLine *weights,
                                             GwyLine *modulus,
                                             ModuleArgs *args);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("XYZ data 1D FFT correction."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "2.0",
    "Petr Klapetek",
    "2023",
};

GWY_MODULE_QUERY2(module_info, xyz_fft)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_fft",
                          &module_main,
                          N_("/_FFT Filtering..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Filter data using FFT"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static const GwyEnum outputs[] = {
        { N_("Marked"),    OUTPUT_MARKED,   },
        { N_("Unmarked"),  OUTPUT_UNMARKED, },
    };
    static const GwyEnum suppresses[] = {
        { N_("Null"),      SUPPRESS_NULL,         },
        { N_("Suppress"),  SUPPRESS_NEIGBOURHOOD, },
    };
    static const GwyEnum zooms[] = {
        { N_("100 %"),  ZOOM_100, },
        { N_("20 %"),   ZOOM_20,  },
        { N_("1 %"),    ZOOM_1,   },
    };
    static const GwyEnum dirs[] = {
        { N_("X"),      FFT_X,      },
        { N_("Y"),      FFT_Y,      },
        { N_("Values"), FFT_VALUES, },
    };
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, gwy_xyz_func_current());
    gwy_param_def_add_scatter_data(paramdef, PARAM_DATA, "data", _("Value to transform"));
    gwy_param_def_add_gwyenum(paramdef, PARAM_SUPPRESS, "suppress", _("_Suppress type"),
                              suppresses, G_N_ELEMENTS(suppresses), SUPPRESS_NEIGBOURHOOD);
    gwy_param_def_add_gwyenum(paramdef, PARAM_OUTPUT, "output", _("_Filter type"),
                              outputs, G_N_ELEMENTS(outputs), OUTPUT_UNMARKED);
    gwy_param_def_add_gwyenum(paramdef, PARAM_ZOOM, "zoom", _("_Zoom"),
                              zooms, G_N_ELEMENTS(zooms), ZOOM_20);
    gwy_param_def_add_gwyenum(paramdef, PARAM_AXIS, "dir", _("_Apply to"),
                              dirs, G_N_ELEMENTS(dirs), FFT_VALUES);
    gwy_param_def_add_boolean(paramdef, PARAM_LOGSCALE, "logscale", _("_Logarithmic scale"), TRUE);

    return paramdef;
}

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

    g_return_if_fail(mode & RUN_MODES);

    gwy_clear1(args);
    gwy_data_browser_get_current(GWY_APP_SCATTER, &args.scatter,
                                 GWY_APP_SCATTER_ID, &id,
                                 0);
    g_return_if_fail(GWY_IS_SCATTER(args.scatter));

    gint nvalues = gwy_scatter_get_n_values(args.scatter);
    if (!nvalues)
        return;

    args.params = gwy_params_new_from_settings(define_module_params());

    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;
    }

    newid = gwy_file_add_xyz(data, args.result);

    gwy_file_set_visible(data, GWY_FILE_XYZ, newid, TRUE);
    gwy_file_set_title(data, GWY_FILE_XYZ, newid, _("FFT corrected"), TRUE);
    gwy_log_add(data, GWY_FILE_XYZ, id, newid);

    g_object_unref(args.result);

end:
    g_object_unref(args.params);

    if (args.fftinput)
        g_object_unref(args.fftinput);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args, GwyFile *data, gint id)
{
    ModuleGUI gui;

    gui.args = args;
    gui.field = gwy_field_new(10, 10, 10, 10, FALSE);
    gint n = gwy_scatter_get_n_points(args->scatter);
    args->fftinput = gwy_line_new(n, n, FALSE);
    gui.spectrum = gwy_line_new(MAXN, n/2 + 1, FALSE);

    gui.dialog = gwy_dialog_new(_("FFT filtering"));
    GwyDialog *dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_RESET, GWY_STOCK_UPDATE, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    gwy_preview_scatter_to_field(args->scatter, 0, gui.field, PREVIEW_SIZE, PREVIEW_SIZE, GWY_PREVIEW_SCATTER_FILL);
    GtkWidget *dataview = gwy_create_preview(gui.field, NULL, PREVIEW_SIZE);
    gwy_setup_data_view(GWY_DATA_VIEW(dataview), data, GWY_FILE_XYZ, id, GWY_FILE_ITEM_PALETTE);
    GtkWidget *hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(dataview), FALSE);

    gui.gmodel = gwy_graph_model_new();
    // FIXME: There are no actualy units because the filtering is done in sampling units.
    g_object_set(gui.gmodel,
                 "y-logarithmic", gwy_params_get_boolean(args->params, PARAM_LOGSCALE),
                 "axis-label-bottom", "f",
                 NULL);
    GwyGraphCurveModel *gcmodel = gwy_graph_curve_model_new();
    g_object_set(gcmodel, "mode", GWY_GRAPH_CURVE_LINE, "description", "FFT data", NULL);
    gwy_graph_model_add_curve(gui.gmodel, gcmodel);
    g_object_unref(gcmodel);

    GtkWidget *graph = gwy_graph_new(gui.gmodel);
    gwy_graph_enable_user_input(GWY_GRAPH(graph), FALSE);
    gtk_widget_set_size_request(graph, PREVIEW_SIZE, PREVIEW_SIZE);
    gtk_box_pack_start(GTK_BOX(hbox), graph, TRUE, TRUE, 0);

    GtkWidget *area = gwy_graph_get_area(GWY_GRAPH(graph));
    gwy_graph_area_set_status(GWY_GRAPH_AREA(area), GWY_GRAPH_STATUS_XSEL);
    args->graph_selection = gwy_graph_area_get_selection(GWY_GRAPH_AREA(area), GWY_GRAPH_STATUS_XSEL);
    gwy_selection_set_max_objects(args->graph_selection, 20);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
    gwy_dialog_add_content(dialog, hbox, FALSE, FALSE, 4);

    GwyParamTable *table;
    gui.table_axis = table = gwy_param_table_new(args->params);
    gwy_param_table_append_radio(table, PARAM_AXIS);
    gwy_param_table_append_scatter_data(table, PARAM_DATA, args->scatter);

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

    gui.table_options = table = gwy_param_table_new(args->params);
    gwy_param_table_append_radio(table, PARAM_SUPPRESS);
    gwy_param_table_append_radio(table, PARAM_OUTPUT);

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

    gui.table_view = table = gwy_param_table_new(args->params);
    gwy_param_table_append_radio(table, PARAM_ZOOM);
    gwy_param_table_append_checkbox(table, PARAM_LOGSCALE);

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

    g_signal_connect_swapped(gui.table_options, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(gui.table_axis, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(gui.table_view, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_after(dialog, "response", G_CALLBACK(dialog_response), &gui);
    gwy_dialog_set_preview_func(dialog, GWY_PREVIEW_UPON_REQUEST, preview, &gui, NULL);

    gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), GTK_RESPONSE_OK, FALSE);

    GwyDialogOutcome outcome = gwy_dialog_run(dialog);

    g_object_unref(gui.field);

    return outcome;
}

static void
preview(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;

    if (!execute(gui->args, GTK_WINDOW(gui->dialog)))
        return;

    gwy_preview_scatter_to_field(gui->args->result, 0, gui->field, PREVIEW_SIZE, PREVIEW_SIZE,
                                 GWY_PREVIEW_SCATTER_FILL);

    gwy_field_data_changed(gui->field);
    gwy_dialog_have_result(GWY_DIALOG(gui->dialog));
    gtk_dialog_set_response_sensitive(GTK_DIALOG(gui->dialog), GTK_RESPONSE_OK, TRUE);
}

static void
dialog_response(GwyDialog *dialog, gint response, ModuleGUI *gui)
{
    if (response == GWY_RESPONSE_RESET) {
        gint idata = gwy_params_get_int(gui->args->params, PARAM_DATA);

        gwy_selection_clear(gui->args->graph_selection);
        gwy_preview_scatter_to_field(gui->args->scatter, idata, gui->field, PREVIEW_SIZE, PREVIEW_SIZE,
                                     GWY_PREVIEW_SCATTER_FILL);

        gwy_field_data_changed(gui->field);
        gwy_dialog_invalidate(GWY_DIALOG(dialog));
        gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), GTK_RESPONSE_OK, FALSE);
    }
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    if (id < 0 || id == PARAM_ZOOM)
        update_fft_curve(gui);

    if (id < 0 || id == PARAM_AXIS) {
        gwy_param_table_set_sensitive(gui->table_axis, PARAM_DATA,
                                      gwy_params_get_enum(gui->args->params, PARAM_AXIS) == FFT_VALUES);
    }
    if (id < 0 || id == PARAM_AXIS || id == PARAM_DATA) {
        // FIXME: This is wrong. If a calculation is so slow to even have progressbar, is MUST BE QUEUED. It cannot be
        // simply run inside param_changed().
        calculate_fft_curve(gui);
        update_fft_curve(gui);
    }

    if (id < 0 || id == PARAM_LOGSCALE) {
        gboolean is_log = gwy_params_get_boolean(gui->args->params, PARAM_LOGSCALE);
        g_object_set(gui->gmodel,
                     "y-logarithmic", is_log,
                     "axis-label-left", is_log ? "log W" : "W",
                     NULL);
    }
}

static void
calculate_fft_curve(ModuleGUI *gui)
{
    ModuleArgs *args = gui->args;
    GwyScatter *scatter = args->scatter;
    GwyLine *fftinput = args->fftinput;
    FFTWhat what = gwy_params_get_enum(args->params, PARAM_AXIS);
    gint idata = gwy_params_get_int(args->params, PARAM_DATA);

    gwy_app_wait_start(GTK_WINDOW(gui->dialog), _("Calculating spectrum..."));

    gsize n = gwy_scatter_get_n_points(scatter);

    GwyLine *rfft = gwy_line_new(n, n, FALSE);
    GwyLine *ifft = gwy_line_new(n, n, FALSE);
    copy_data_to_line(scatter, what, idata, fftinput);
    gwy_line_add(gui->args->fftinput, -gwy_line_mean(fftinput));

    gwy_line_fft_raw(gui->args->fftinput, NULL, rfft, ifft, GWY_TRANSFORM_DIRECTION_FORWARD);
    gdouble *realdata = gwy_line_get_data(rfft);
    gdouble *imagdata = gwy_line_get_data(ifft);

    gsize linen = gwy_line_get_res(gui->spectrum);
    gdouble *spectrumdata = gwy_line_get_data(gui->spectrum);
    gsize avn = n/linen/2;

    for (gsize k = 0; k < linen; k++) {
        gdouble avg = 0.0;
        for (gsize m = 0; m < avn; m++) {
            gsize i = k*avn + m;
            avg += sqrt(realdata[i]*realdata[i] + imagdata[i]*imagdata[i]);
        }
        spectrumdata[k] = avg/avn;
    }
    gwy_line_data_changed(gui->spectrum);

    gwy_app_wait_finish();
    g_object_unref(rfft);
    g_object_unref(ifft);
}

static void
update_fft_curve(ModuleGUI *gui)
{
    gint n = gwy_line_get_res(gui->spectrum);
    FFTZoomType zoom = gwy_params_get_enum(gui->args->params, PARAM_ZOOM);
    GwyGraphCurveModel *gcmodel = gwy_graph_model_get_curve(gui->gmodel, 0);

    if (zoom == ZOOM_20)
        n = n/5;
    else if (zoom == ZOOM_1)
        n = n/100;

    gwy_graph_curve_model_set_data_from_line(gcmodel, gui->spectrum, 0, n);
}

static gboolean
execute(ModuleArgs *args, GtkWindow *wait_window)
{
    GwyScatter *scatter = args->scatter;
    FFTWhat what = gwy_params_get_enum(args->params, PARAM_AXIS);
    gint idata = gwy_params_get_int(args->params, PARAM_DATA);
    gboolean ok = FALSE;

    g_clear_object(&args->result);

    // If we are going to create entire new data, extract a single channel. Do not just copy a bunch of other,
    // unmodified data there.
    gsize n = gwy_scatter_get_n_points(scatter);
    const GwyXY *xy = gwy_scatter_get_xy_const(scatter);
    const gdouble *z = gwy_scatter_get_data_const(scatter, idata);
    GwyScatter *result = args->result = gwy_scatter_new_sized(1, n);
    GwyXY *xy_result = gwy_scatter_get_xy(result);
    gdouble *z_result = gwy_scatter_get_data(result, 0);
    gwy_assign(xy_result, xy, n);
    gwy_assign(z_result, z, n);

    gwy_unit_assign(gwy_scatter_get_unit_xy(result), gwy_scatter_get_unit_xy(scatter));
    gwy_unit_assign(gwy_scatter_get_unit_data(result, 0), gwy_scatter_get_unit_data(scatter, idata));
    const gchar *label;
    if ((label = gwy_scatter_get_data_label(scatter, idata)))
        gwy_scatter_set_data_label(result, 0, label);

    gwy_app_wait_start(wait_window, _("Filtering..."));

    GwyLine *rfft = gwy_line_new(n, n, FALSE);
    GwyLine *ifft = gwy_line_new(n, n, FALSE);
    GwyLine *rresult = gwy_line_new(n, n, FALSE);
    GwyLine *iresult = gwy_line_new(n, n, FALSE);
    GwyLine *weights = gwy_line_new(n/2 + 1, n/2 + 1, TRUE);
    GwyLine *fullspectrum = gwy_line_new(n/2 + 1, n/2 + 1, FALSE);

    copy_data_to_line(scatter, what, idata, args->fftinput);
    gwy_line_fft_raw(args->fftinput, NULL, rfft, ifft, GWY_TRANSFORM_DIRECTION_FORWARD);

    if (!gwy_app_wait_set_fraction(0.4))
        goto end;

    double *fsdata = gwy_line_get_data(fullspectrum);
    gdouble *realdata = gwy_line_get_data(rfft);
    gdouble *imagdata = gwy_line_get_data(ifft);
    for (gsize k = 0; k < n/2; k++)
        fsdata[k] = sqrt(realdata[k]*realdata[k] + imagdata[k]*imagdata[k]);

    calculate_weights(weights, fullspectrum, args);

    gdouble *weightdata = gwy_line_get_data(weights);

    if (!gwy_app_wait_set_fraction(0.6))
        goto end;

    for (gsize k = 0; k < n/2; k++) {
        realdata[k] *= weightdata[k];
        imagdata[k] *= weightdata[k];

        realdata[n-k-1] *= weightdata[k];
        imagdata[n-k-1] *= weightdata[k];
    }
    if (!gwy_app_wait_set_fraction(0.7))
        goto end;

    gwy_line_fft_raw(rfft, ifft, rresult, iresult, GWY_TRANSFORM_DIRECTION_BACKWARD);

    if (!gwy_app_wait_set_fraction(0.9))
        goto end;

    gdouble *rresultdata = gwy_line_get_data(rresult);

    if (what == FFT_VALUES)
        gwy_assign(z_result, rresultdata, n);
    else if (what == FFT_X) {
       for (gsize k = 0; k < n; k++)
          xy_result[k].x = rresultdata[k];
    }
    else if (what == FFT_Y) {
       for (gsize k = 0; k < n; k++)
          xy_result[k].y = rresultdata[k];
    }

    ok = TRUE;

end:
    gwy_app_wait_finish();
    g_clear_object(&rfft);
    g_clear_object(&ifft);
    g_clear_object(&rresult);
    g_clear_object(&iresult);
    g_clear_object(&weights);
    g_clear_object(&fullspectrum);

    return ok;
}

static void
copy_data_to_line(GwyScatter *scatter, FFTWhat what, gint idata, GwyLine *line)
{
    gsize n = gwy_scatter_get_n_points(scatter);
    gwy_line_resize(line, n);
    gdouble *linedata = gwy_line_get_data(line);

    if (what == FFT_VALUES)
        gwy_assign(linedata, gwy_scatter_get_data_const(scatter, idata), n);
    else {
        const GwyXY *xy = gwy_scatter_get_xy_const(scatter);
        if (what == FFT_X) {
            for (gsize k = 0; k < n; k++)
                linedata[k] = xy[k].x;
        }
        else if (what == FFT_Y) {
            for (gsize k = 0; k < n; k++)
                linedata[k] = xy[k].y;
        }
    }
}

/* XXX: This function is identical among image 1D FFT filter, volume 1D FFT filter and XYZ FFT.
 * Make a library function! */
static void
calculate_weights(GwyLine *weights, GwyLine *modulus, ModuleArgs *args)
{
    GwyFFTFilt1DSuppressType suppres = gwy_params_get_enum(args->params, PARAM_SUPPRESS);
    GwyFFTFilt1DOutputType output = gwy_params_get_enum(args->params, PARAM_OUTPUT);
    GwySelection *selection = args->graph_selection;
    gint res, k, nsel;
    gdouble sel[2], *w;
    gint fill_from, fill_to;

    res = gwy_line_get_res(weights);
    nsel = gwy_selection_get_data(selection, NULL);
    for (k = 0; k < nsel; k++) {
        gwy_selection_get_object(selection, k, sel);
        GWY_ORDER(gdouble, sel[0], sel[1]);
        fill_from = MAX(0, gwy_line_rtoi(weights, sel[0]));
        fill_from = MIN(res, fill_from);
        fill_to = MIN(res, gwy_line_rtoi(weights, sel[1]));
        gwy_line_part_fill(weights, fill_from, fill_to - fill_from, 1.0);
    }

    w = gwy_line_get_data(weights);
    if (output == OUTPUT_MARKED) {
        for (k = 0; k < res; k++)
            w[k] = 1.0 - w[k];
    }

    /* For Suppress, interpolate PSDF linearly between endpoints.  Since we pass weights to the filter, not PSDF
     * itself, we have to divide to get the weight. */
    if (suppres == SUPPRESS_NEIGBOURHOOD) {
        GwyLine *buf = gwy_line_copy(modulus);
        gdouble *b, *m;

        /*invert the weights as the laplace correction treats it as a mask*/
        for (k = 0; k < res; k++)
            w[k] = 1.0 - w[k];

        gwy_line_laplace_solve(buf, weights);
        b = gwy_line_get_data(buf);
        m = gwy_line_get_data(modulus);

        for (k = 0; k < res; k++)
            w[k] = (m[k] > 0.0 ? fmin(b[k]/m[k], 1.0) : 0.0);
        g_object_unref(buf);
    }
}

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