/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - sch-rnd (executable)
 *  Copyright (C) 2023 Tibor 'Igor2' Palinkas
 *
 *  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., 31 Milk Street, # 960789 Boston, MA 02196 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
 */

/* Included from font.c */

#include <librnd/core/actions.h>
#include "funchash_core.h"


static const char csch_acts_FontInfo[] = "FontInfo(TextWidth|TextHeight, str, [penname])";
static const char csch_acth_FontInfo[] = "Test-render str and return width or height.";
static fgw_error_t csch_act_FontInfo(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	csch_sheet_t *sheet = CSCH_ACT_SHEET;
	rnd_font_t *f;
	rnd_coord_t cx[4], cy[4];
	csch_cpen_t *pen;
	int op;
	const char *text_str, *penname = "sheet-decor";

	RND_ACT_CONVARG(1, FGW_KEYWORD, FontInfo, op = fgw_keyword(&argv[1]));
	RND_ACT_CONVARG(2, FGW_STR, FontInfo, text_str = argv[2].val.str);
	RND_ACT_MAY_CONVARG(3, FGW_STR, FontInfo, penname = argv[3].val.str);

	switch(op) {
		case F_TextWidth:
		case F_TextHeight:

			pen = csch_pen_get(sheet, &sheet->direct, penname);
			if (penname == NULL)
				return FGW_ERR_ARG_CONV;

			f = rf_resolve_pen(&sheet->hidlib, pen);
			if (f == NULL)
				return FGW_ERR_ARG_CONV;

			res->type = FGW_LONG;
			if (op == F_TextHeight) {
				res->val.nat_long = P2C(f->height);
				return 0;
			}

			rnd_font_string_bbox(cx, cy, f, (const unsigned char *)text_str, 0, 0, 1, 1, 0, 0, 0, 0);
			cx[0] = 0; /* undo the effect of left side whitespace: we started to render from 0;0 */
			res->val.nat_long = P2C(cx[1] - cx[0]);
			return 0;

		default:
			return FGW_ERR_ARG_CONV;
	
	}

	return -1;
}

static rnd_action_t font_action_list[] = {
	{"FontInfo", csch_act_FontInfo, csch_acth_FontInfo, csch_acts_FontInfo}
};

void sch_rnd_font_act_init2(void)
{
	RND_REGISTER_ACTIONS(font_action_list, NULL);
}
