/*
 *  $Id: xyz_valueops.c 30111 2026-06-22 11:02:00Z yeti-dn $
 *  Copyright (C) 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 {
    PARAM_DATA,
    PARAM_OPERAND,
    PARAM_SORT_SOURCE,
    PARAM_ASCENDING,
    PARAM_NEW_NAME,

    MESSAGE_NO_DATA,
    BUTTON_RENAME,
};

enum {
    RESPONSE_RENAME = GWY_RESPONSE_USER
};

// The same as in relate, except we do not use zero (index).
typedef enum {
    COORDINATE_X     = 1,
    COORDINATE_Y     = 2,
    COORDINATE_VALUE = 3,
} CoordinateType;

typedef struct {
    GwyParams *params;
    GwyScatter *scatter;
} ModuleArgs;

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

static gboolean         module_register     (void);
static GwyParamDef*     define_remove_params(void);
static GwyParamDef*     define_rename_params(void);
static GwyParamDef*     define_stack_params (void);
static GwyParamDef*     define_sort_params  (void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static GwyDialogOutcome remove_run_gui      (ModuleArgs *args);
static void             rename_run_gui      (ModuleArgs *args);
static GwyDialogOutcome stack_run_gui       (ModuleArgs *args);
static GwyDialogOutcome sort_run_gui        (ModuleArgs *args);
static gboolean         stack_data_filter   (GwyFile *data,
                                             gint id,
                                             gpointer user_data);
static void             stack_param_changed (ModuleGUI *gui,
                                             gint id);
static void             rename_param_changed(ModuleGUI *gui,
                                             gint id);
static void             rename_response     (ModuleGUI *gui,
                                             gint response);
static gint             compare_x           (const gdouble *xydataa,
                                             const gdouble *xydatab,
                                             gpointer user_data);
static gint             compare_y           (const gdouble *xydataa,
                                             const gdouble *xydatab,
                                             gpointer user_data);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("XYZ data size reduction by skipping points."),
    "Yeti <yeti@gwyddion.net>",
    "1.0",
    "David Nečas (Yeti)",
    "2026",
};

GWY_MODULE_QUERY2(module_info, xyz_valueops)

static gboolean
module_register(void)
{
    gwy_xyz_func_register("xyz_remove",
                          module_main,
                          N_("/_Value Set/_Remove Value..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Remove a value plane from XYZ data"));
    gwy_xyz_func_register("xyz_rename",
                          module_main,
                          N_("/_Value Set/Re_name..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Rename XYZ data values"));
    gwy_xyz_func_register("xyz_stack",
                          module_main,
                          N_("/_Value Set/_Stack..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Combine data planes from compatible XYZ data"));
    gwy_xyz_func_register("xyz_sort",
                          module_main,
                          N_("/_Sort..."),
                          NULL,
                          RUN_MODES,
                          GWY_MENU_FLAG_XYZ,
                          N_("Order XYZ data points by a coordinate or value"));

    return TRUE;
}

static GwyParamDef*
define_remove_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", _("Value to remove"));

    return paramdef;
}

static GwyParamDef*
define_rename_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", _("Value to rename"));
    gwy_param_def_add_string(paramdef, PARAM_NEW_NAME, "name", _("New name"),
                             GWY_PARAM_STRING_NULL_IS_EMPTY, NULL, "");

    return paramdef;
}

static GwyParamDef*
define_stack_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_xyz_id(paramdef, PARAM_OPERAND, "operand", _("Other XYZ data"));

    return paramdef;
}

static GwyParamDef*
define_sort_params(void)
{
    static const GwyEnum sources[] = {
        { N_("X-coordinate"),  COORDINATE_X,     },
        { N_("Y-coordinate"),  COORDINATE_Y,     },
        { N_("Value"),         COORDINATE_VALUE, },
    };

    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_gwyenum(paramdef, PARAM_SORT_SOURCE, "sort_source", _("Sort by"),
                              sources, G_N_ELEMENTS(sources), COORDINATE_X);
    gwy_param_def_add_boolean(paramdef, PARAM_ASCENDING, "ascending", _("Ascending order"), TRUE);
    gwy_param_def_add_scatter_data(paramdef, PARAM_DATA, "data", _("Value"));

    return paramdef;
}

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

    const gchar *name = gwy_xyz_func_current();
    g_return_if_fail(mode & RUN_MODES);

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

    gint nvalues = gwy_scatter_get_n_values(args.scatter);
    if (gwy_strequal(name, "xyz_remove")) {
        if (nvalues < 2)
            return;
        args.params = gwy_params_new_from_settings(define_remove_params());
        outcome = remove_run_gui(&args);
    }
    else if (gwy_strequal(name, "xyz_rename")) {
        if (!nvalues)
            return;
        args.params = gwy_params_new_from_settings(define_rename_params());
        rename_run_gui(&args);
        outcome = GWY_DIALOG_CANCEL;
    }
    else if (gwy_strequal(name, "xyz_stack")) {
        args.params = gwy_params_new_from_settings(define_stack_params());
        outcome = stack_run_gui(&args);
    }
    else if (gwy_strequal(name, "xyz_sort")) {
        args.params = gwy_params_new_from_settings(define_sort_params());
        if (!nvalues) {
            gwy_params_set_enum(args.params, PARAM_SORT_SOURCE, COORDINATE_X);
        }
        outcome = sort_run_gui(&args);
    }

    gwy_params_save_to_settings(args.params);
    if (outcome == GWY_DIALOG_CANCEL)
        goto end;

    gwy_app_undo_qcheckpointv(GWY_DICT(data), 1, &quark);

    if (gwy_strequal(name, "xyz_remove")) {
        gint toremove = gwy_params_get_int(args.params, PARAM_DATA);
        gwy_scatter_remove_values(args.scatter, toremove, 1);
    }
    else if (gwy_strequal(name, "xyz_stack")) {
        GwyScatter *operand = gwy_params_get_xyz(args.params, PARAM_OPERAND);
        gwy_scatter_stack(args.scatter, &operand, 1);
    }
    else if (gwy_strequal(name, "xyz_sort")) {
        CoordinateType coordtype = gwy_params_get_enum(args.params, PARAM_SORT_SOURCE);
        gint idata = gwy_params_get_int(args.params, PARAM_DATA);
        gboolean ascending = gwy_params_get_boolean(args.params, PARAM_ASCENDING);
        gint sign = ascending ? 1 : -1;

        if (coordtype == COORDINATE_X)
            gwy_scatter_sort(args.scatter, compare_x, GINT_TO_POINTER(sign));
        else if (coordtype == COORDINATE_Y)
            gwy_scatter_sort(args.scatter, compare_y, GINT_TO_POINTER(sign));
        else
            gwy_scatter_sort_by_value(args.scatter, idata, ascending);

        gwy_scatter_xy_changed(args.scatter);
    }

    gwy_scatter_data_changed(args.scatter);
    gwy_log_add(data, GWY_FILE_XYZ, id, id);

end:
    g_object_unref(args.params);
}

static GwyDialogOutcome
remove_run_gui(ModuleArgs *args)
{
    GwyDialog *dialog = GWY_DIALOG(gwy_dialog_new(_("Remove XYZ Value")));
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    GwyParamTable *table = gwy_param_table_new(args->params);

    gwy_param_table_append_scatter_data(table, PARAM_DATA, args->scatter);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, TRUE, 0);

    return gwy_dialog_run(dialog);
}

static void
rename_run_gui(ModuleArgs *args)
{
    ModuleGUI gui;

    gui.args = args;
    gui.dialog = gwy_dialog_new(_("Rename XYZ Value"));
    GwyDialog *dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CLOSE, 0);

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

    gwy_param_table_append_scatter_data(table, PARAM_DATA, args->scatter);
    gwy_param_table_append_entry(table, PARAM_NEW_NAME);
    gwy_param_table_append_button(table, BUTTON_RENAME, -1, RESPONSE_RENAME, _("_Rename"));
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, TRUE, 0);

    g_signal_connect_swapped(table, "param-changed", G_CALLBACK(rename_param_changed), &gui);
    g_signal_connect_swapped(dialog, "response", G_CALLBACK(rename_response), &gui);

    gwy_dialog_run(dialog);
}

static GwyDialogOutcome
stack_run_gui(ModuleArgs *args)
{
    ModuleGUI gui;

    gui.args = args;
    gui.dialog = gwy_dialog_new(_("Stack XYZ Data"));
    GwyDialog *dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

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

    gwy_param_table_append_xyz_id(table, PARAM_OPERAND);
    gwy_param_table_data_id_set_filter(table, PARAM_OPERAND, stack_data_filter, args, NULL);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_message(table, MESSAGE_NO_DATA, NULL);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, TRUE, 0);

    g_signal_connect_swapped(table, "param-changed", G_CALLBACK(stack_param_changed), &gui);

    return gwy_dialog_run(dialog);
}

static GwyDialogOutcome
sort_run_gui(ModuleArgs *args)
{
    GwyDialog *dialog = GWY_DIALOG(gwy_dialog_new(_("Sort XYZ Data")));
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    GwyParamTable *table = gwy_param_table_new(args->params);

    gwy_param_table_append_radio(table, PARAM_SORT_SOURCE);
    gwy_param_table_append_scatter_data(table, PARAM_DATA, args->scatter);
    gwy_param_table_append_checkbox(table, PARAM_ASCENDING);
    if (!gwy_scatter_get_n_values(args->scatter)) {
        gwy_param_table_radio_set_sensitive(table, PARAM_SORT_SOURCE, COORDINATE_VALUE, FALSE);
        gwy_param_table_set_sensitive(table, PARAM_DATA, FALSE);
    }
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), FALSE, TRUE, 0);

    return gwy_dialog_run(dialog);
}

static void
stack_param_changed(ModuleGUI *gui, gint id)
{
    ModuleArgs *args = gui->args;
    GwyParamTable *table = gui->table;

    if (id < 0 || id == PARAM_OPERAND) {
        gboolean have_data = !gwy_params_data_id_is_none(args->params, PARAM_OPERAND);
        gwy_param_table_set_label(table, MESSAGE_NO_DATA,
                                  have_data ? NULL : _("No XYZ data with compatible XY found."));
        gtk_dialog_set_response_sensitive(GTK_DIALOG(gui->dialog), GTK_RESPONSE_OK, have_data);
    }
}

static void
rename_param_changed(ModuleGUI *gui, gint id)
{
    ModuleArgs *args = gui->args;
    GwyParamTable *table = gui->table;

    if (id < 0 || id == PARAM_DATA) {
        gint i = gwy_params_get_int(args->params, PARAM_DATA);
        const gchar *label = gwy_scatter_get_data_label(args->scatter, i);
        gwy_param_table_set_string(table, PARAM_NEW_NAME, label);
    }
}

static void
rename_response(ModuleGUI *gui, gint response)
{
    ModuleArgs *args = gui->args;
    GwyParamTable *table = gui->table;

    if (response == RESPONSE_RENAME) {
        gint i = gwy_params_get_int(args->params, PARAM_DATA);
        const gchar *oldlabel = gwy_scatter_get_data_label(args->scatter, i);
        const gchar *newlabel = gwy_params_get_string(args->params, PARAM_NEW_NAME);
        if (!g_strcmp0(newlabel, oldlabel))
            return;

        gwy_scatter_set_data_label(args->scatter, i, newlabel);
        gwy_param_table_scatter_data_refresh(table, PARAM_DATA, TRUE);
    }
}

static gboolean
stack_data_filter(GwyFile *data, gint id, gpointer user_data)
{
    ModuleArgs *args = (ModuleArgs*)user_data;
    GwyScatter *scatter = args->scatter;
    GwyScatter *otherscatter = gwy_file_get_xyz(data, id);

    if (otherscatter == scatter)
        return FALSE;

    return !gwy_scatter_is_incompatible(otherscatter, scatter,
                                        GWY_DATA_MISMATCH_LATERAL | GWY_DATA_MISMATCH_POINTS);
}

static gint
compare_x(const gdouble *xydataa, const gdouble *xydatab, gpointer user_data)
{
    gint sign = GPOINTER_TO_INT(user_data);
    if (xydataa[0] < xydatab[0])
        return -sign;
    if (xydataa[0] > xydatab[0])
        return sign;
    return 0;
}

static gint
compare_y(const gdouble *xydataa, const gdouble *xydatab, gpointer user_data)
{
    gint sign = GPOINTER_TO_INT(user_data);
    if (xydataa[1] < xydatab[1])
        return -sign;
    if (xydataa[1] > xydatab[1])
        return sign;
    return 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 : */
