/*
 *  $Id: xyz_tcrop.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,
};

typedef enum {
    DISPLAY_X      = 0,
    DISPLAY_Y      = 1,
    DISPLAY_VALUES = 2,
} CropDisplay;

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

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

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table_axis;
    GwyParamTable *table_range;
    GwyParamTable *table_options;
    GwyField *preview;
    GwyNield *mask;
    GwyValueFormat *vf;
    GwyGraphModel *gmodel;
} 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 void             update_graph_curve      (ModuleGUI *gui);

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

GWY_MODULE_QUERY2(module_info, xyz_tcrop)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_tcrop",
                          module_main,
                          N_("/Crop as _Series..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Crop XYZ data as series"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;
    static const GwyEnum displays[] = {
        { N_("X"),      DISPLAY_X,      },
        { N_("Y"),      DISPLAY_Y,      },
        { N_("Values"), DISPLAY_VALUES, },
    };

    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"), 0, G_MAXDOUBLE, G_MAXDOUBLE);
    gwy_param_def_add_double(paramdef, PARAM_TO, NULL, _("To"), 0, G_MAXDOUBLE, G_MAXDOUBLE);
    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);
    gwy_param_def_add_gwyenum(paramdef, PARAM_DISPLAY, "dir", _("_Show"),
                              displays, G_N_ELEMENTS(displays), DISPLAY_X);
    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;
    gwy_param_table_set_double(gui->table_range, PARAM_FROM, 0);
    gwy_param_table_set_double(gui->table_range, PARAM_TO, gwy_scatter_get_n_points(args->scatter));
}

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

    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(_("Crop XYZ Data as Series"));
    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);
    hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(dataview), FALSE);

    gui.gmodel = gwy_graph_model_new();
    g_object_set(gui.gmodel,
                 "axis-label-bottom", "sample",
                 NULL);
    GwyGraphCurveModel *gcmodel = gwy_graph_curve_model_new();
    g_object_set(gcmodel, "mode", GWY_GRAPH_CURVE_LINE, "description", "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), TRUE);
    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, 1);

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

    gui.table_axis = table = gwy_param_table_new(args->params);
    gwy_param_table_append_radio(table, PARAM_DISPLAY);
    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_range = table = gwy_param_table_new(args->params);
    gwy_create_graph_xrange_with_params(table, PARAM_FROM, PARAM_TO, GWY_GRAPH(graph), gui.gmodel);
    gwy_param_table_append_info(table, INFO_NPOINTS, _("Number of points"));
    set_full_range(&gui);

    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_checkbox(table, PARAM_MASK_EMPTY);
    gwy_param_table_append_checkbox(table, PARAM_UPDATE);

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

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

    g_signal_connect_swapped(gui.table_axis, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(gui.table_range, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(gui.table_options, "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);

    return outcome;
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    if (id < 0 || id == PARAM_DISPLAY) {
        gwy_param_table_set_sensitive(gui->table_axis, PARAM_DATA,
                                      gwy_params_get_enum(gui->args->params, PARAM_DISPLAY) == DISPLAY_VALUES);
    }
    if (id < 0 || id == PARAM_DISPLAY)
        update_graph_curve(gui);

    if (id < 0 || id == PARAM_FROM || id == PARAM_TO) {
        gchar *s = g_strdup_printf("%lu", (gulong)(gwy_params_get_double(gui->args->params, PARAM_TO)
                                                   - gwy_params_get_double(gui->args->params, PARAM_FROM)));
        gwy_param_table_info_set_valuestr(gui->table_range, INFO_NPOINTS, s);
        g_free(s);
    }

    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 from = (gint)gwy_params_get_double(params, PARAM_FROM);
    gint to = (gint)gwy_params_get_double(params, PARAM_TO);
    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);
    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 (k < from || 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_range, INFO_NPOINTS, s);
    g_free(s);
}

static void
update_graph_curve(ModuleGUI *gui)
{
    ModuleArgs *args = gui->args;
    GwyGraphCurveModel *gcmodel = gwy_graph_model_get_curve(gui->gmodel, 0);
    GwyLine *line;
    gint display = gwy_params_get_enum(gui->args->params, PARAM_DISPLAY);
    gint idata = gwy_params_get_int(args->params, PARAM_DATA);
    GwyScatter *scatter = args->scatter;
    const GwyXY *xy = gwy_scatter_get_xy_const(scatter);
    const gdouble *z = gwy_scatter_get_data_const(scatter, idata);
    gint nvals = gwy_scatter_get_n_points(scatter);
    gdouble *linedata;
    gint k, n, m, ndiv = 1;

    if (nvals > 5000000)
        ndiv = 10000;
    else if (nvals > 500000)
        ndiv = 1000;
    else if (nvals > 50000)
        ndiv = 100;
    else if (nvals > 5000)
        ndiv = 10;

    line = gwy_line_new(nvals/ndiv, nvals, FALSE);
    linedata = gwy_line_get_data(line);

    m = 0;
    for (n = 0; n < nvals/ndiv; n++) {
        linedata[n] = 0;
        if (display == DISPLAY_X)
            for (k = 0; k < ndiv; k++)
                linedata[n] += xy[m++].x;
        else if (display == DISPLAY_Y)
            for (k = 0; k < ndiv; k++)
                linedata[n] += xy[m++].y;
        else
            for (k = 0; k < ndiv; k++)
                linedata[n] += z[m++];

         if (ndiv > 1)
             linedata[n] /= ndiv;
    }

    gwy_graph_curve_model_set_data_from_line(gcmodel, line, 0, 0);
    g_object_unref(line);
}

static void
execute(ModuleArgs *args)
{
    gint i;
    gsize k, count = 0;
    GwyScatter *scatter = args->scatter;
    gint nvals = gwy_scatter_get_n_values(scatter);
    gint n = gwy_scatter_get_n_points(scatter);
    gint from = (gint)gwy_params_get_double(args->params, PARAM_FROM);
    gint to = (gint)gwy_params_get_double(args->params, PARAM_TO);
    GwyXY *newxy;
    const gdouble *vals;
    gdouble *newvals;
    const GwyXY *xy = gwy_scatter_get_xy_const(scatter);

    g_clear_object(&args->result);

    for (k = 0; k < n; k++) {
        if (k < from || k > to)
            continue;
        count++;
    }

    args->result = gwy_scatter_new_sized(nvals, count);

    newxy = gwy_scatter_get_xy(args->result);
    gwy_assign(newxy, xy + from, count);
    for (i = 0; i < nvals; i++) {
        vals = gwy_scatter_get_data_const(scatter, i);
        newvals = gwy_scatter_get_data(args->result, i);
        gwy_assign(newvals, vals + from, count);
    }
}

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