/*
 *  $Id: cmap_fit.c 25639 2023-09-07 12:23:42Z yeti-dn $
 *  Copyright (C) 2021 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 <string.h>
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <gwy.h>
#include "libgwyddion/omp.h"

#define RUN_MODES (GWY_RUN_INTERACTIVE)

enum {
    PARAM_ORDINATE,
    PARAM_SEGMENT,
    PARAM_ENABLE_SEGMENT,
    INFO_RESULT,
};

typedef struct {
    GwyParams *params;
    GwyLawn *lawn;
    gint nsegments;
} ModuleArgs;

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

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static GwyBrick*        execute             (ModuleArgs *args);
static GwyDialogOutcome run_gui             (ModuleArgs *args);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Volumize curves."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "1.0",
    "David Nečas (Yeti) & Petr Klapetek",
    "2024",
};

GWY_MODULE_QUERY2(module_info, cmap_volumize)

static gboolean
module_register(void)
{
    gwy_cmap_func_register("cmap_volumize",
                           module_main,
                           N_("/_Volumize Curves..."),
                           NULL,
                           RUN_MODES,
                           GWY_MENU_FLAG_CMAP,
                           N_("Volumize curves"));

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

    gwy_param_def_add_lawn_curve(paramdef, PARAM_ORDINATE, "ordinate", _("Ordinate"));
    gwy_param_def_add_lawn_segment(paramdef, PARAM_SEGMENT, "segment", NULL);
    gwy_param_def_add_boolean(paramdef, PARAM_ENABLE_SEGMENT, "enable_segment", NULL, FALSE);

    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    ModuleArgs args;
    GwyLawn *lawn = NULL;
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    gint id, newid, ordinate, segment;
    gboolean segment_enabled;
    GwyBrick *brick;
    const gchar *segmentlabel;

    g_return_if_fail(mode & RUN_MODES);

    gwy_clear1(args);
    gwy_data_browser_get_current(GWY_APP_LAWN, &lawn,
                                 GWY_APP_LAWN_ID, &id,
                                 0);
    g_return_if_fail(GWY_IS_LAWN(lawn));

    args.lawn = lawn;
    args.nsegments = gwy_lawn_get_n_segments(lawn);
    args.params = gwy_params_new_from_settings(define_module_params());

    if (mode == GWY_RUN_INTERACTIVE) {
        outcome = run_gui(&args);
        gwy_params_save_to_settings(args.params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    if (outcome != GWY_DIALOG_HAVE_RESULT) {
        brick = execute(&args);
        if (brick) {
            newid = gwy_file_add_volume(data, brick, NULL);
            gwy_file_set_visible(data, GWY_FILE_VOLUME, newid, TRUE);

            segment_enabled = args.nsegments ? gwy_params_get_boolean(args.params, PARAM_ENABLE_SEGMENT) : FALSE;
            segment = segment_enabled ? gwy_params_get_int(args.params, PARAM_SEGMENT) : -1;
            ordinate = gwy_params_get_int(args.params, PARAM_ORDINATE);

            //printf("se %d  s %d o %d\n", segment_enabled, segment, ordinate);

            gchar *title;
            if (segment_enabled) {
                segmentlabel = gwy_lawn_get_segment_label(lawn, segment);
                if (segmentlabel)
                    title = g_strdup_printf("%s: %s", gwy_lawn_get_curve_label(lawn, ordinate), segmentlabel);
                else {
                    title = g_strdup_printf(_("%s: (Segment %d)"),
                                            gwy_lawn_get_curve_label(lawn, ordinate), segment + 1);
                }
            }
            else
                title = g_strdup(gwy_lawn_get_curve_label(lawn, ordinate));

            gwy_file_set_title(data, GWY_FILE_VOLUME, newid, title, TRUE);
            g_free(title);
            gwy_file_sync_items(data, GWY_FILE_CMAP, id,
                                data, GWY_FILE_VOLUME, newid,
                                GWY_FILE_ITEM_PALETTE, FALSE);

            g_object_unref(brick);
        }
    }

end:
    g_object_unref(args.params);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args)
{
    GtkWidget *hbox;
    GwyParamTable *table;
    GwyDialog *dialog;
    ModuleGUI gui;

    gwy_clear1(gui);
    gui.args = args;

    gui.dialog = gwy_dialog_new(_("Volumize Curves"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
    gwy_dialog_add_content(GWY_DIALOG(gui.dialog), hbox, TRUE, TRUE, 0);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 20);
    gwy_dialog_add_content(GWY_DIALOG(gui.dialog), hbox, TRUE, TRUE, 4);

    table = gui.table = gwy_param_table_new(args->params);
    gwy_param_table_append_lawn_curve(table, PARAM_ORDINATE, args->lawn);
    if (args->nsegments) {
        gwy_param_table_append_lawn_segment(table, PARAM_SEGMENT, args->lawn);
        gwy_param_table_add_enabler(table, PARAM_ENABLE_SEGMENT, PARAM_SEGMENT);
    }
    gwy_param_table_append_info(table, INFO_RESULT, "");

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

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

    return gwy_dialog_run(dialog);
}

static gboolean
check_brickability(GwyLawn *lawn, gboolean segment_enabled, gint segment,
                   gint *bxres, gint *byres, gint *bzres)
{
    gint xres = gwy_lawn_get_xres(lawn);
    gint yres = gwy_lawn_get_yres(lawn);
    gint from, end, col, row, ndata0, ndata;
    const gint *segments;

    *bxres = xres;
    *byres = yres;
    *bzres = 0;

    ndata0 = gwy_lawn_get_curve_length(lawn, 0, 0);
    if (segment_enabled && segment >= 0) {
        segments = gwy_lawn_get_segments(lawn, 0, 0, NULL);
        from = segments[2*segment];
        end = segments[2*segment + 1];
        ndata0 = end - from;
    }
    if (ndata0 <= 0)
        return FALSE;

    for (col = 0; col < xres; col++) {
        for (row = 0; row < yres; row++) {
            ndata = gwy_lawn_get_curve_length(lawn, col, row);
            if (segment >= 0) {
                segments = gwy_lawn_get_segments(lawn, col, row, NULL);
                from = segments[2*segment];
                end = segments[2*segment + 1];
                ndata = end - from;
            }
            if (ndata != ndata0)
                return FALSE;
        }
    }
    *bzres = ndata0;

    return TRUE;
}

static void
param_changed(ModuleGUI *gui, G_GNUC_UNUSED gint id)
{
    GwyParams *params = gui->args->params;
    gint xres, yres, zres;
    gchar result[50];
    gboolean segment_enabled = gui->args->nsegments ? gwy_params_get_boolean(params, PARAM_ENABLE_SEGMENT) : FALSE;
    gint segment = segment_enabled ? gwy_params_get_int(params, PARAM_SEGMENT) : -1;

    if (!check_brickability(gui->args->lawn, segment_enabled, segment, &xres, &yres, &zres))
        gwy_param_table_info_set_valuestr(gui->table, INFO_RESULT, _("Cannot convert to volume data"));
    else {
        g_snprintf(result, sizeof(result), _("Volume data size: %d × %d × %d"), xres, yres, zres);
        gwy_param_table_info_set_valuestr(gui->table, INFO_RESULT, result);
    }

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

static GwyBrick*
execute(ModuleArgs *args)
{
    GwyParams *params = args->params;
    gint ordinate = gwy_params_get_int(params, PARAM_ORDINATE);
    gboolean segment_enabled = args->nsegments ? gwy_params_get_boolean(params, PARAM_ENABLE_SEGMENT) : FALSE;
    gint segment = segment_enabled ? gwy_params_get_int(params, PARAM_SEGMENT) : -1;
    GwyLawn *lawn = args->lawn;
    GwyBrick *brick;
    gint col, row, lev, xres, yres, zres, from;
    const gint *segments;
    const gdouble *ydata;
    gdouble *bdata;

    if (!check_brickability(args->lawn, segment_enabled, segment, &xres, &yres, &zres))
        return NULL;

    brick = gwy_brick_new(xres, yres, zres, gwy_lawn_get_xreal(lawn), gwy_lawn_get_yreal(lawn), zres, FALSE);
    bdata = gwy_brick_get_data(brick);

    for (col = 0; col < xres; col++) {
        for (row = 0; row < yres; row++) {
            ydata = gwy_lawn_get_curve_data_const(lawn, col, row, ordinate, NULL);
            from = 0;
            if (segment_enabled && segment >= 0) {
                segments = gwy_lawn_get_segments(lawn, col, row, NULL);
                from = segments[2*segment];
            }
            for (lev = 0; lev < zres; lev++)
                bdata[col + xres*row + xres*yres*lev] = ydata[from + lev];
        }
    }

    gwy_unit_assign(gwy_brick_get_unit_x(brick), gwy_lawn_get_unit_xy(lawn));
    gwy_unit_assign(gwy_brick_get_unit_y(brick), gwy_lawn_get_unit_xy(lawn));
    gwy_unit_assign(gwy_brick_get_unit_w(brick), gwy_lawn_get_unit_curve(lawn, ordinate));

    return brick;
}

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