#include <stdio.h>
#include <librnd/core/safe_fs.h>
#include <librnd/hid/hid.h>
#include <librnd/hid/hid_dad.h>

#include <plugins/lib_plot/plot_preview.h>

static long fnc_cos(long x)
{
	return cos((double)x/200.0) * 200.0;
}

static long fnc_sq(long x)
{
	double tmp = (double)x / 100;
	return tmp*tmp;
}

static int fill(plot_trace_t *tr, plot_trdata_t *trdata, plot_which_t which, long from, long len, long (*fnc)(long x))
{
	double tmp[1024];
	long n;
	plot_pos_t pw;

	if (plot_write_init(&pw, tr, trdata, PLOT_MAIN, 0, 0, tmp, sizeof(tmp)/sizeof(tmp[0])) != 0)
		return -1;

	for(n = 0; n < len; n++)
		plot_write(&pw, fnc(n));

	plot_flush(&pw);
	return 0;
}



typedef struct plotdlg_ctx_s {
	RND_DAD_DECL_NOINIT(dlg)
	plot_preview_t prv;
	FILE *fc;
} plotdlg_ctx_t;

static void plotdlg_close_cb(void *caller_data, rnd_hid_attr_ev_t ev)
{
	plotdlg_ctx_t *ctx = caller_data;
	plot_data_uninit(&ctx->prv.pdata);
	fclose(ctx->fc);
	free(ctx);
}

static void readout_cb(plot_preview_t *ctx, int trace_idx, long x, double y)
{
	rnd_trace("[%d] %d %f\n", trace_idx, x, y);
}

static void plot_test_dlg(void)
{
	rnd_hid_dad_buttons_t clbtn[] = {{"Close", 0}, {NULL, 0}};
	plotdlg_ctx_t *ctx = calloc(sizeof(plotdlg_ctx_t), 1);
	static rnd_box_t prvbb = {0, 0, 200*200, 200*200};
	plot_trace_t *tr;
	plot_trdata_t *td;

	ctx->fc = rnd_fopen(NULL, "cache", "w+");
	ctx->prv.user_data = ctx;
	ctx->prv.readout_cb = readout_cb;
	plot_data_init(&ctx->prv.pdata, 2);

#define LEN 10000

	tr = &ctx->prv.pdata.trace[0];
	plot_trace_init(tr, ctx->fc);
	td = plot_trdata_alloc(tr, 0, LEN);
	fill(tr, td, PLOT_MAIN, 0, LEN, fnc_cos);

	tr = &ctx->prv.pdata.trace[1];
	plot_trace_init(tr, ctx->fc);
	td = plot_trdata_alloc(tr, 0, LEN);
	fill(tr, td, PLOT_MAIN, 0, LEN, fnc_sq);

	RND_DAD_BEGIN_VBOX(ctx->dlg);
		RND_DAD_COMPFLAG(ctx->dlg, RND_HATF_EXPFILL);

		RND_DAD_PREVIEW(ctx->dlg, plot_preview_expose_cb, plot_mouse_cb, NULL, NULL, &prvbb, 150, 150, &ctx->prv);
			RND_DAD_COMPFLAG(ctx->dlg, RND_HATF_EXPFILL);


		RND_DAD_BUTTON_CLOSES(ctx->dlg, clbtn);
	RND_DAD_END(ctx->dlg);

	RND_DAD_DEFSIZE(ctx->dlg, 200, 300);
	RND_DAD_NEW("PlotTest", ctx->dlg, "Plot test", ctx, 0, plotdlg_close_cb); /* type=dummy */


}

const char csch_acts_PlotTest[] = "PlotTest()";
const char csch_acth_PlotTest[] = "Open the plot test dialog\n";
fgw_error_t csch_act_PlotTest(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	plot_test_dlg();
	return 0;
}
