/*
 *                            COPYRIGHT
 *
 *  pcb-rnd, interactive printed circuit board design
 *  Copyright (C) 2016,2019,2020 Tibor 'Igor2' Palinkas
 *  Copyright (C) 2022, 2023 Tibor 'Igor2' Palinkas (slight modifications for sch-rnd)
 *
 *  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.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/pcb-rnd
 *    lead developer: http://repo.hu/projects/pcb-rnd/contact.html
 *    mailing list: pcb-rnd (at) list.repo.hu (send "subscribe")
 */

/* Query language - actions */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libcschem/config.h>
#include <libcschem/actions_csch.h>
#include <sch-rnd/conf_core.h>
#include <sch-rnd/buffer.h>
#include <librnd/core/actions.h>
#include "query.h"
#include "query_y.h"
#include "query_exec.h"
#include "query_access.h"
#include <libcschem/concrete.h>
#include <libcschem/cnc_any_obj.h>
#include "dlg_search.h"
#include <librnd/core/compat_misc.h>
#include <librnd/core/project.h>
#include <librnd/hid/hid.h>

static const char csch_acts_query[] =
	"query(dump, expr) - dry run: compile and dump an expression\n"
	"query(eval|evalidp, expr) - compile and evaluate an expression and print a list of results on stdout\n"
	"query(count, expr) - compile and evaluate an expression and return the number of matched objects (-1 on error)\n"
	"query(select|unselect|view, expr) - select or unselect or build a view of objects matching an expression\n"
	"query(append, idplist, expr) - compile and run expr and append the idpath of resulting objects on idplist\n"
	;
static const char csch_acth_query[] = "Perform various queries on concrete model data.";

typedef struct {
	int trues, falses;
	unsigned print_idpath:1;
} eval_stat_t;

static void count_cb(void *user_ctx, pcb_qry_val_t *res, csch_chdr_t *current)
{
	eval_stat_t *st = (eval_stat_t *)user_ctx;
	int t;

	t = pcb_qry_is_true(res);
	if (t)
		st->trues++;
}

static void eval_cb(void *user_ctx, pcb_qry_val_t *res, csch_chdr_t *current)
{
	char *resv;
	eval_stat_t *st = (eval_stat_t *)user_ctx;
	int t;

	if (res->type == PCBQ_VT_VOID) {
		printf(" <void>\n");
		st->falses++;
		return;
	}

	if (st->print_idpath && (res->type == PCBQ_VT_OBJ)) {
		char *idps = csch_chdr_to_oidpath_str(res->data.obj);
		st->trues++;
		printf(" <obj %s>\n", idps);
		free(idps);
		return;
	}

	if ((res->type != PCBQ_VT_COORD) && (res->type != PCBQ_VT_LONG)) {
		st->trues++;
		resv = pcb_query_sprint_val(res);
		printf(" %s\n", resv);
		free(resv);
		return;
	}

	t = pcb_qry_is_true(res);
	printf(" %s", t ? "true" : "false");
	if (t) {
		resv = pcb_query_sprint_val(res);
		printf(" (%s)\n", resv);
		free(resv);
		st->trues++;
	}
	else {
		printf("\n");
		st->falses++;
	}
}

typedef struct {
	csch_sheet_t *sheet;
	rnd_cardinal_t cnt;
	enum { FLAGOP_SELECT, FLAGOP_UNSELECT } act;
} flagop_t;

static void flagop_cb(void *user_ctx, pcb_qry_val_t *res, csch_chdr_t *obj)
{
	flagop_t *sel = (flagop_t *)user_ctx;
	if (!pcb_qry_is_true(res))
		return;

	{
		switch(sel->act) {
			case FLAGOP_SELECT:
				if (!obj->selected) {
					csch_cobj_select(sel->sheet, obj);
					sel->cnt++;
				}
				break;
			case FLAGOP_UNSELECT:
				if (obj->selected) {
					csch_cobj_unselect(sel->sheet, obj);
					sel->cnt++;
				}
				break;
		}
	}
}

static void append_cb(void *user_ctx, pcb_qry_val_t *res, csch_chdr_t *current)
{
	csch_oidpath_list_t *list = user_ctx;
	csch_oidpath_t *idp;

	if (!pcb_qry_is_true(res))
		return;

	idp = calloc(sizeof(csch_oidpath_t), 1);
	csch_oidpath_from_obj(idp, current);
	csch_oidpath_list_append(list, idp);
}

static void view_cb(void *user_ctx, pcb_qry_val_t *res, csch_chdr_t *current)
{
	vtp0_t *arr = user_ctx;

	if (!pcb_qry_is_true(res))
		return;

	vtp0_append(arr, current);
}

pcb_qry_node_t *pcb_query_compile(const char *script)
{
	pcb_qry_node_t *prg = NULL;

	pcb_qry_set_input(script);
	qry_parse(&prg);
	return prg;
}

int pcb_qry_run_script(pcb_qry_exec_t *ec, csch_sheet_t *sheet, const char *script, const char *scope, void (*cb)(void *user_ctx, pcb_qry_val_t *res, csch_chdr_t *current), void *user_ctx)
{
	pcb_qry_node_t *prg = NULL;
	int res;
	int project_scope = 0, bufno = -1; /* empty scope means board */

	if (script == NULL) {
		rnd_message(RND_MSG_ERROR, "Compilation error: no script specified.\n");
		return -1;
	}

	pcb_qry_set_input(script);
	qry_parse(&prg);

	if (prg == NULL) {
		rnd_message(RND_MSG_ERROR, "Compilation error.\n");
		return -1;
	}

	/* decode scope and set bufno */
	if ((scope != NULL) && (*scope != '\0')) {
		if (strcmp(scope, "project") == 0) {
			bufno = -1;
			project_scope = 1;
		}
		else if (strcmp(scope, "sheet") == 0) bufno = -1;
		else if (strcmp(scope, "sheet-indirect") == 0) bufno = -2;
		else if (strncmp(scope, "buffer", 6) == 0) {
			scope += 6;
			if (*scope != '\0') {
				char *end;
				bufno = strtol(scope, &end, 10);
				if (*end != '\0') {
					rnd_message(RND_MSG_ERROR, "Invalid buffer number: '%s': not an integer\n", scope);
					pcb_qry_n_free(prg);
					return -1;
				}
				bufno--;
				if ((bufno < 0) || (bufno >= SCH_RND_BUFFER_MAX)) {
					rnd_message(RND_MSG_ERROR, "Invalid buffer number: '%d' out of range 1..%d\n", bufno+1, SCH_RND_BUFFER_MAX);
					pcb_qry_n_free(prg);
					return -1;
				}
			}
			else
				bufno = conf_core.editor.buffer_number;
		}
		else {
			rnd_message(RND_MSG_ERROR, "Invalid scope: '%s': must be board or buffer or bufferN\n", scope);
			pcb_qry_n_free(prg);
			return -1;
		}
	}

	if (project_scope) {
		long n;
		rnd_project_t *prj = sheet->hidlib.project;

		for(n = 0; n < prj->designs.used; n++) {
			int r = pcb_qry_run(ec, prj->designs.array[n], prg, bufno, cb, user_ctx);
			if (r < 0) {
				res = r;
				break;
			}
			res += r;
		}
	}
	else
		res = pcb_qry_run(ec, sheet, prg, bufno, cb, user_ctx);
	pcb_qry_n_free(prg);
	return res;
}

extern int pcb_qry_fnc_getconf(pcb_qry_exec_t *ectx, int argc, pcb_qry_val_t *argv, pcb_qry_val_t *res);
static void pcb_qry_extract_defs_(htsi_t *dst, pcb_qry_node_t *nd, int *total)
{
	if (nd->type == PCBQ_FCALL) {
		pcb_qry_node_t *fname = nd->data.children;
		if ((fname->type == PCBQ_FNAME) && (fname->precomp.fnc.bui == pcb_qry_fnc_getconf) && (fname->next->type == PCBQ_DATA_STRING)) {
			const char *name = fname->next->data.str;
			htsi_entry_t *e;
			if (strncmp(name, "design/drc/", 11) == 0) {
				name += 11;
				e = htsi_getentry(dst, name);
				if (e == NULL) {
					htsi_set(dst, rnd_strdup(name), 0);
					e = htsi_getentry(dst, name);
				}
				e->value++;
				(*total)++;
			}
		}
	}

	/* RULE needs special recursion */
	if (nd->type == PCBQ_RULE) {
		for(nd = nd->data.children->next->next; nd != NULL; nd = nd->next)
			pcb_qry_extract_defs_(dst, nd, total);
		return;
	}

	/* recurse */
	if (pcb_qry_nodetype_has_children(nd->type))
		for(nd = nd->data.children; nd != NULL; nd = nd->next)
			pcb_qry_extract_defs_(dst, nd, total);
}

int pcb_qry_extract_defs(htsi_t *dst, const char *script)
{
	pcb_qry_node_t *prg = NULL;
	int total = 0;

	pcb_qry_set_input(script);
	qry_parse(&prg);
	if (prg == NULL)
		return -1;

	pcb_qry_extract_defs_(dst, prg, &total);

	pcb_qry_n_free(prg);
	return total;
}


static fgw_error_t csch_act_query(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	rnd_design_t *hidlib = RND_ACT_DESIGN;
	csch_sheet_t *sheet = (csch_sheet_t *)hidlib;
	const char *cmd, *arg = NULL, *scope = NULL;
	flagop_t sel;

	sel.cnt = 0;

	RND_ACT_CONVARG(1, FGW_STR, query, cmd = argv[1].val.str);
	RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);

	if (strcmp(cmd, "version") == 0) {
		RND_ACT_IRES(0100); /* 1.0 */
		return 0;
	}

	if (strcmp(cmd, "dump") == 0) {
		pcb_qry_node_t *prg = NULL;

		RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);
		printf("Script dump: '%s'\n", arg);
		pcb_qry_set_input(arg);
		qry_parse(&prg);
		if (prg != NULL) {
			pcb_qry_dump_tree(" ", prg);
			pcb_qry_n_free(prg);
			RND_ACT_IRES(0);
		}
		else
			RND_ACT_IRES(1);
		return 0;
	}

	if ((strcmp(cmd, "eval") == 0) || (strcmp(cmd, "evalidp") == 0)) {
		int errs;
		eval_stat_t st;

		RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);
		RND_ACT_MAY_CONVARG(3, FGW_STR, query, scope = argv[3].val.str);

		memset(&st, 0, sizeof(st));
		st.print_idpath = (cmd[4] != '\0');
		printf("Script eval: '%s' scope='%s'\n", arg, scope == NULL ? "" : scope);
		errs = pcb_qry_run_script(NULL, sheet, arg, scope, eval_cb, &st);

		if (errs < 0)
			printf("Failed to run the query\n");
		else
			printf("eval statistics: true=%d false=%d errors=%d\n", st.trues, st.falses, errs);
		RND_ACT_IRES(0);
		return 0;
	}

	if ((strcmp(cmd, "count") == 0)) {
		int errs;
		eval_stat_t st;

		RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);
		RND_ACT_MAY_CONVARG(3, FGW_STR, query, scope = argv[3].val.str);

		memset(&st, 0, sizeof(st));
		st.print_idpath = (cmd[4] != '\0');
		errs = pcb_qry_run_script(NULL, sheet, arg, scope, count_cb, &st);

		if (errs == 0)
			RND_ACT_IRES(st.trues);
		else
			RND_ACT_IRES(-1);
		return 0;
	}


	if (strcmp(cmd, "select") == 0) {
		sel.sheet = sheet;
		sel.act = FLAGOP_SELECT;

		RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);
		RND_ACT_MAY_CONVARG(3, FGW_STR, query, scope = argv[3].val.str);

		if (pcb_qry_run_script(NULL, sheet, arg, scope, flagop_cb, &sel) < 0)
			printf("Failed to run the query\n");
		if (sel.cnt > 0) {
			csch_sheet_set_changed(sheet, rnd_true);
			if (RND_HAVE_GUI_ATTR_DLG)
				rnd_hid_redraw(hidlib);
		}
		RND_ACT_IRES(0);
		return 0;
	}

	if (strcmp(cmd, "unselect") == 0) {
		sel.sheet = sheet;
		sel.act = FLAGOP_UNSELECT;

		RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);
		RND_ACT_MAY_CONVARG(3, FGW_STR, query, scope = argv[3].val.str);

		if (pcb_qry_run_script(NULL, sheet, arg, scope, flagop_cb, &sel) < 0)
			printf("Failed to run the query\n");
		if (sel.cnt > 0) {
			csch_sheet_set_changed(sheet, rnd_true);
			if (RND_HAVE_GUI_ATTR_DLG)
				rnd_hid_redraw(hidlib);
		}
		RND_ACT_IRES(0);
		return 0;
	}

	if (strcmp(cmd, "append") == 0) {
		csch_oidpath_list_t *list;

		RND_ACT_CONVARG(2, FGW_IDPATH_LIST, query, list = fgw_idpath_list(&argv[2]));
		RND_ACT_MAY_CONVARG(3, FGW_STR, query, arg = argv[3].val.str);
		RND_ACT_MAY_CONVARG(4, FGW_STR, query, scope = argv[4].val.str);

		if (!fgw_ptr_in_domain(&rnd_fgw, &argv[2], RND_PTR_DOMAIN_IDPATH_LIST))
			return FGW_ERR_PTR_DOMAIN;

		if (pcb_qry_run_script(NULL, sheet, arg, scope, append_cb, list) < 0)
			RND_ACT_IRES(1);
		else
			RND_ACT_IRES(0);
		return 0;
	}

	if (strcmp(cmd, "view") == 0) {
		fgw_arg_t args[4], ares;
		vtp0_t arr = {0};
		RND_ACT_MAY_CONVARG(2, FGW_STR, query, arg = argv[2].val.str);
		RND_ACT_MAY_CONVARG(3, FGW_STR, query, scope = argv[3].val.str);
		if (pcb_qry_run_script(NULL, sheet, arg, scope, view_cb, &arr) >= 0) {
			args[1].type = FGW_STR; args[1].val.str = "objarr";
			fgw_ptr_reg(&rnd_fgw, &args[2], CSCH_PTR_DOMAIN_COBJ_ARR, FGW_PTR | FGW_STRUCT, &arr);
			rnd_actionv_bin(RND_ACT_DESIGN, "TreeDialog", &ares, 3, args);
			fgw_ptr_unreg(&rnd_fgw, &args[2], CSCH_PTR_DOMAIN_COBJ_ARR);
			vtp0_uninit(&arr);
			RND_ACT_IRES(0);
		}
		else
			RND_ACT_IRES(1);

		vtp0_uninit(&arr);
		return 0;
	}

	RND_ACT_FAIL(query);
}

static const char *PTR_DOMAIN_PCFIELD = "ptr_domain_query_precompiled_field";

static pcb_qry_node_t *field_comp(const char *fields)
{
	char fname[64], *fno;
	const char *s;
	int len = 1, flen = 0, idx = 0, quote = 0;
	pcb_qry_node_t *res;

	if (*fields == '.') fields++;
	if (*fields == '\0')
		return NULL;

	for(s = fields; *s != '\0'; s++) {
		if (*s == '.') {
			len++;
			if (len > 16)
				return NULL; /* too many fields chained */
			if (flen >= sizeof(fname))
				return NULL; /* field name segment too long */
			flen = 0;
		}
		else
			flen++;
	}

	res = calloc(sizeof(pcb_qry_node_t), len);
	fno = fname;
	for(s = fields;; s++) {
		if ((quote == 0) && ((*s == '.') || (*s == '\0'))) {
			*fno = '\0';
			if (idx > 0)
				res[idx-1].next = &res[idx];
			res[idx].type = PCBQ_FIELD;
			res[idx].precomp.fld = query_fields_sphash(fname);
/*rnd_trace("[%d/%d] '%s' -> %d\n", idx, len, fname, res[idx].precomp.fld);*/
			if (res[idx].precomp.fld < 0) /* if compilation failed, this will need to be evaluated run-time, save as string */
				res[idx].data.str = rnd_strdup(fname);
			fno = fname;
			if (*s == '\0')
				break;
			idx++;
			if (s[1] == '\"') {
				quote = s[1];
				s++;
			}
		}
		else {
			if (*s == quote)
				quote = 0;
			else
				*fno++ = *s;
		}
	}

	return res;
}

static void field_free(pcb_qry_node_t *fld)
{
	pcb_qry_node_t *f;
	for(f = fld; f != NULL; f = f->next)
		if (f->data.str != NULL)
			free((char *)f->data.str);
	free(fld);
}


static void val2fgw(fgw_arg_t *dst, pcb_qry_val_t *src)
{
	switch(src->type) {
		case PCBQ_VT_COORD:
			dst->type = FGW_COORD_;
			fgw_coord(dst) = src->data.crd;
			break;
		case PCBQ_VT_LONG:
			dst->type = FGW_LONG;
			dst->val.nat_long = src->data.lng;
			break;
		case PCBQ_VT_DOUBLE:
			dst->type = FGW_DOUBLE;
			dst->val.nat_double = src->data.dbl;
			break;
		case PCBQ_VT_STRING:
			if (src->data.str != NULL) {
				dst->type = FGW_STR | FGW_DYN;
				dst->val.str = rnd_strdup(src->data.str);
			}
			else {
				dst->type = FGW_PTR;
				dst->val.ptr_void = NULL;
			}
			break;
		case PCBQ_VT_VOID:
		case PCBQ_VT_OBJ:
		case PCBQ_VT_LST:
		default:;
			break;
	}
}

static const char csch_acts_QueryObj[] = "QueryObj(idpath, [.fieldname|fieldID])";
static const char csch_acth_QueryObj[] = "Return the value of a field of an object, addressed by the object's idpath and the field's name or precompiled ID. Returns NIL on error.";
static fgw_error_t csch_act_QueryObj(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	rnd_design_t *hidlib = RND_ACT_DESIGN;
	csch_sheet_t *sheet = (csch_sheet_t *)hidlib;
	csch_oidpath_t *idp;
	pcb_qry_node_t *fld = NULL;
	pcb_qry_val_t obj;
	pcb_qry_val_t val;
	int free_fld = 0;

	RND_ACT_CONVARG(1, FGW_IDPATH, QueryObj, idp = fgw_idpath(&argv[1]));

	if ((argv[2].type & FGW_STR) == FGW_STR) {
		const char *field;
		RND_ACT_CONVARG(2, FGW_STR, QueryObj, field = argv[2].val.str);
		if (field == NULL)
			goto err;
		if (*field != '.')
			goto id;
		fld = field_comp(field);
		free_fld = 1;
	}
	else if ((argv[2].type & FGW_PTR) == FGW_PTR) {
		id:;
		RND_ACT_CONVARG(2, FGW_PTR, QueryObj, fld = argv[2].val.ptr_void);
		if (!fgw_ptr_in_domain(&rnd_fgw, &argv[2], PTR_DOMAIN_PCFIELD))
			return FGW_ERR_PTR_DOMAIN;
	}

	if ((fld == NULL) || (!fgw_ptr_in_domain(&rnd_fgw, &argv[1], RND_PTR_DOMAIN_IDPATH))) {
		if (free_fld)
			field_free(fld);
		return FGW_ERR_PTR_DOMAIN;
	}

	obj.type = PCBQ_VT_OBJ;
	obj.data.obj = csch_oidpath_resolve(sheet, idp);
	if (obj.data.obj == NULL)
		goto err;

	{
		int ret;
		pcb_qry_exec_t ec;

		pcb_qry_init(&ec, sheet, NULL, -1);
		ret = pcb_qry_obj_field(NULL, &obj, fld, &val);
		pcb_qry_uninit(&ec);

		if (ret != 0)
			goto err;
	}

	if (free_fld)
		field_free(fld);

	val2fgw(res, &val);
	return 0;

	err:;
		if (free_fld)
			field_free(fld);
		res->type = FGW_PTR;
		res->val.ptr_void = NULL;
		return 0;
}

static const char csch_acts_QueryCompileField[] =
	"QueryCompileField(compile, fieldname)\n"
	"QueryCompileField(free, fieldID)";
static const char csch_acth_QueryCompileField[] = "With \"compile\": precompiles textual field name to field ID; with \"free\": frees the memory allocated for a previously precompiled fieldID.";
static fgw_error_t csch_act_QueryCompileField(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	const char *cmd, *fname;
	pcb_qry_node_t *fld;

	RND_ACT_CONVARG(1, FGW_STR, QueryCompileField, cmd = argv[1].val.str);
	switch(*cmd) {
		case 'c': /* compile */
			RND_ACT_CONVARG(2, FGW_STR, QueryCompileField, fname = argv[2].val.str);
			fld = field_comp(fname);
			fgw_ptr_reg(&rnd_fgw, res, PTR_DOMAIN_PCFIELD, FGW_PTR | FGW_STRUCT, fld);
			return 0;
		case 'f': /* free */
			if (!fgw_ptr_in_domain(&rnd_fgw, &argv[2], PTR_DOMAIN_PCFIELD))
				return FGW_ERR_PTR_DOMAIN;
			RND_ACT_CONVARG(2, FGW_PTR, QueryCompileField, fld = argv[2].val.ptr_void);
			fgw_ptr_unreg(&rnd_fgw, &argv[2], PTR_DOMAIN_PCFIELD);
			field_free(fld);
			return 0;
		default:
			return FGW_ERR_ARG_CONV;
	}
	return 0;
}

/* in net_len.c */
extern const char csch_acts_QueryCalcNetLen[];
extern const char csch_acth_QueryCalcNetLen[];
extern fgw_error_t csch_act_QueryCalcNetLen(fgw_arg_t *res, int argc, fgw_arg_t *argv);

rnd_action_t query_action_list[] = {
	{"query", csch_act_query, csch_acth_query, csch_acts_query},
	{"QueryObj", csch_act_QueryObj, csch_acth_QueryObj, csch_acts_QueryObj},
	{"QueryCompileField", csch_act_QueryCompileField, csch_acth_QueryCompileField, csch_acts_QueryCompileField},
	{"SearchDialog", csch_act_SearchDialog, csch_acth_SearchDialog, csch_acts_SearchDialog}
};

void query_action_reg(const char *cookie)
{
	RND_REGISTER_ACTIONS(query_action_list, cookie)
}
