/*
 *  $Id: xyz_tcut.c 30124 2026-06-23 11:47:09Z klapetek $
 *  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,
};

enum {
    PARAM_DATA,
    PARAM_FROM,
    PARAM_TO,
    PARAM_UPDATE,
    PARAM_MASK_EMPTY,
    INFO_NPOINTS,
};

typedef struct {
    GwyParams *params;
    GwyScatter *scatter;
    GwyScatter *result;

    gdouble vfscaled_from;
    gdouble vfscaled_to;
    gint idata;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table;
    GwyField *preview;
    GwyNield *mask;
    GwyValueFormat *vf;
} 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             preview             (gpointer user_data);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("XYZ data filter by value."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "2.0",
    "Petr Klapetek & David Nečas (Yeti)",
    "2023",
};

GWY_MODULE_QUERY2(module_info, xyz_tcut)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_tcut",
                          module_main,
                          N_("/_Filter by Value..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Filter XYZ data"));

    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_xyz_func_current());
    gwy_param_def_add_scatter_data(paramdef, PARAM_DATA, "data", _("Series data"));
    gwy_param_def_add_double(paramdef, PARAM_FROM, NULL, _("From"), -G_MAXDOUBLE, G_MAXDOUBLE, 0.0);
    gwy_param_def_add_double(paramdef, PARAM_TO, NULL, _("To"), -G_MAXDOUBLE, G_MAXDOUBLE, 0.0);
    gwy_param_def_add_instant_updates(paramdef, PARAM_UPDATE, "update", NULL, TRUE);
    gwy_param_def_add_boolean(paramdef, PARAM_MASK_EMPTY, "mask_empty", _("_Mask empty regions"), FALSE);
    return paramdef;
}

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

    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));
    if (!gwy_scatter_get_n_values(args.scatter))
        return;

    args.params = gwy_params_new_from_settings(define_module_params());

    outcome = run_gui(&args, data, id);
    gwy_params_save_to_settings(args.params);
    if (outcome == GWY_DIALOG_CANCEL)
        goto end;

    if (outcome == GWY_DIALOG_PROCEED)
        execute(&args);

    gint 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, _("Series cropped"), TRUE);
    gwy_file_sync_items(data, GWY_FILE_XYZ, id,
                        data, GWY_FILE_XYZ, newid,
                        GWY_FILE_ITEM_PALETTE, FALSE);
    gwy_log_add(data, GWY_FILE_XYZ, id, newid);

    g_object_unref(args.result);

end:
    g_object_unref(args.params);
}

static void
set_full_range(ModuleGUI *gui)
{
    ModuleArgs *args = gui->args;
    gint i = gwy_params_get_int(args->params, PARAM_DATA);
    gdouble vmin, vmax;
    gwy_scatter_min_max(args->scatter, i, &vmin, &vmax);
    GwyValueFormat *vf = gui->vf;
    gwy_scatter_get_value_format_data(args->scatter, i, GWY_UNIT_FORMAT_VFMARKUP, vf);

    gwy_param_table_slider_restrict_range(gui->table, PARAM_FROM,
                                          vmin/vf->magnitude, vmax/vf->magnitude);
    gwy_param_table_slider_restrict_range(gui->table, PARAM_TO,
                                          vmin/vf->magnitude, vmax/vf->magnitude);

    gwy_param_table_set_unitstr(gui->table, PARAM_FROM, vf->units);
    gwy_param_table_set_unitstr(gui->table, PARAM_TO, vf->units);
    gwy_param_table_set_double(gui->table, PARAM_FROM, vmin/vf->magnitude);
    gwy_param_table_set_double(gui->table, PARAM_TO, vmax/vf->magnitude);
}

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

    gwy_clear1(gui);
    gui.args = args;
    gui.vf = gwy_value_format_new(1.0, 3, "");
    gui.preview = gwy_field_new(PREVIEW_SIZE, PREVIEW_SIZE, PREVIEW_SIZE, PREVIEW_SIZE, TRUE);
    gui.mask = gwy_field_new_nield_alike(gui.preview);
    gui.dialog = gwy_dialog_new(_("Filter XYZ Data by Value"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_UPDATE, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    GtkWidget *dataview = gwy_create_preview(gui.preview, gui.mask, 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.table = table = gwy_param_table_new(args->params);
    gwy_param_table_append_scatter_data(table, PARAM_DATA, args->scatter);
    // FIXME: This would be nicer as sliders, but we then need to reconfigure them correctly when PARAM_DATA changes.
    gwy_param_table_append_slider(table, PARAM_FROM);
    gwy_param_table_append_slider(table, PARAM_TO);
    gwy_param_table_append_info(table, INFO_NPOINTS, _("Number of points"));
    set_full_range(&gui);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_checkbox(table, PARAM_MASK_EMPTY);
    gwy_param_table_append_checkbox(table, PARAM_UPDATE);
    gwy_param_table_append_separator(table);

    gwy_preview_scatter_to_field(args->scatter, gwy_params_get_int(args->params, PARAM_DATA), gui.preview,
                                 PREVIEW_SIZE, PREVIEW_SIZE, GWY_PREVIEW_SCATTER_FILL);
    gwy_set_data_preview_size(GWY_DATA_VIEW(dataview), PREVIEW_SIZE);

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

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

    GwyDialogOutcome outcome = gwy_dialog_run(dialog);

    g_object_unref(gui.mask);
    args->vfscaled_from = gwy_params_get_double(args->params, PARAM_FROM)*gui.vf->magnitude;
    args->vfscaled_to = gwy_params_get_double(args->params, PARAM_TO)*gui.vf->magnitude;
    gwy_value_format_free(gui.vf);

    return outcome;
}

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

    gwy_dialog_invalidate(GWY_DIALOG(gui->dialog));
}

static void
preview(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;
    ModuleArgs *args = gui->args;
    GwyScatter *scatter = args->scatter;
    GwyParams *params = args->params;
    gint idata = gwy_params_get_int(args->params, PARAM_DATA);
    gdouble from = gwy_params_get_double(params, PARAM_FROM)*gui->vf->magnitude;
    gdouble to = gwy_params_get_double(params, PARAM_TO)*gui->vf->magnitude;
    gboolean mask_empty = gwy_params_get_boolean(params, PARAM_MASK_EMPTY);
    GwyNield *mask = gui->mask;

    if (!mask_empty) {
        gwy_nield_clear(mask);
        gwy_nield_data_changed(mask);
        return;
    }

    GwyField *field = gui->preview;
    gint xres = gwy_field_get_xres(field), yres = gwy_field_get_yres(field);
    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);

    const GwyXY *xy = gwy_scatter_get_xy_const(scatter);
    const gdouble *vdata = gwy_scatter_get_data_const(scatter, idata);
    gsize n = gwy_scatter_get_n_points(scatter);

    gwy_nield_clear(mask);
    gint *mdata = gwy_nield_get_data(mask);
    gsize count = 0;
    for (gsize k = 0; k < n; k++) {
        if (vdata[k] < from || vdata[k] > to)
            continue;

        gdouble x = (xy[k].x - xoff)/xreal*xres, y = (xy[k].y - yoff)/yreal*yres;
        if (x < 0.0 || x >= xres || y < 0.0 || y >= yres)
            continue;

        gint i = (gint)floor(y), j = (gint)floor(x);
        i = CLAMP(i, 0, yres-1);
        j = CLAMP(j, 0, xres-1);
        mdata[i*xres + j]++;
        count++;
    }

    gwy_nield_invert(mask);
    gwy_nield_data_changed(mask);

    gchar *s = g_strdup_printf("%lu", (gulong)count);
    gwy_param_table_info_set_valuestr(gui->table, INFO_NPOINTS, s);
    g_free(s);
}

static gboolean
value_in_range(G_GNUC_UNUSED const GwyXY *xy,
               const gdouble *values,
               gpointer user_data)
{
    ModuleArgs *args = (ModuleArgs*)user_data;
    gdouble value = values[args->idata];
    return value >= args->vfscaled_from && value <= args->vfscaled_to;
}

static void
execute(ModuleArgs *args)
{
    GwyScatter *scatter = args->scatter;
    g_clear_object(&args->result);
    args->result = gwy_scatter_copy(scatter);
    args->idata = gwy_params_get_int(args->params, PARAM_DATA);
    gwy_scatter_filter(args->result, value_in_range, args);
}

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