/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - place predefined groups
 *  Copyright (C) 2022 Tibor 'Igor2' Palinkas
 *
 *  (Supported by NLnet NGI0 PET Fund in 2022)
 *
 *  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/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */


#include <libcschem/config.h>

#include <genregex/regex_sei.h>

#include <libcschem/search.h>
#include <libcschem/util_grp.h>
#include <librnd/core/actions.h>
#include <librnd/core/plugins.h>

#include <sch-rnd/funchash_core.h>
#include <sch-rnd/draw.h>
#include <sch-rnd/crosshair.h>

static const char sch_place_cookie[] = "place plugin";


static fgw_error_t place_action(fgw_arg_t *res, int argc, fgw_arg_t *argv, int (*placer)(csch_sheet_t *sheet, csch_cgrp_t *parent, csch_coord_t ox, csch_coord_t oy))
{
	rnd_design_t *hidlib = RND_ACT_DESIGN;
	csch_sheet_t *sheet = (csch_sheet_t *)hidlib;
	csch_cgrp_t *parent;
	csch_coord_t x = 0, y = 0;
	int rv = -1, target = F_Sheet;

	if (argc > 1)
		target = fgw_keyword(&argv[1]);

	uundo_freeze_serial(&sheet->undo);
	switch(target) {
		case F_Buffer:
			rnd_message(RND_MSG_ERROR, "not yet implemented, sorry\n");
			goto error;
		case F_Sheet:
			parent = &sheet->direct;
			x = P2C(sch_rnd_crosshair_x);
			y = P2C(sch_rnd_crosshair_y);
			break;

		default:
			rnd_message(RND_MSG_ERROR, "PlaceTerminal: wrong first arg\n");
			goto error;
	}

	rv = placer(sheet, parent, x, y);

	error:;

	uundo_unfreeze_serial(&sheet->undo);
	if (rv == 0)
		uundo_inc_serial(&sheet->undo);

	RND_ACT_IRES(rv);
	return 0;
}

#include "attrib.c"
#include "terminal.c"

static rnd_action_t sch_place_action_list[] = {
	{"PlaceAttrib", csch_act_PlaceAttrib, csch_acth_PlaceAttrib, csch_acts_PlaceAttrib},
	{"PlaceTerminal", csch_act_PlaceTerminal, csch_acth_PlaceTerminal, csch_acts_PlaceTerminal}
};

int pplg_check_ver_place(int ver_needed) { return 0; }

void pplg_uninit_place(void)
{
	rnd_remove_actions_by_cookie(sch_place_cookie);
}

int pplg_init_place(void)
{
	RND_API_CHK_VER;

	RND_REGISTER_ACTIONS(sch_place_action_list, sch_place_cookie);
	return 0;
}

