/*
 * dml - Dialog Markup Language
 *
 * $Id: button.c,v 1.3 2002/07/29 13:07:05 malekith Exp $
 * Author: Michal Moskal <malekith@pld-linux.org>
 * include COPYING-GNU
 */

#include "pi.h"

void pi_button_draw(struct pi_button *self)
{
	int c1, c2;
	int x, y, n;
	
	pi_locate((struct pi_object*)self, &x, &y);
	if (pi_is_active((struct pi_object*)self)) {
		c1 = pi_color_abutton;
		c2 = pi_color_abutton_hl;
	} else {
		c1 = pi_color_button;
		c2 = pi_color_button_hl;
	}
	
	pi_color(c1);
	pi_putch('[');
	n = self->pos.w - 2;
	while (n--)
		pi_putch(' ');
	pi_putch(']');
	if (self->caption == 0)
		return;
		
	n = pi_strlen_alt(self->caption);
	if (n > self->pos.w - 2) {
		pi_goto(x + 1, y);
		pi_addstr_alt(self->caption, self->pos.w - 2, c1, c2);
	} else {
		pi_goto(x + (self->pos.w - n) / 2, y);
		pi_addstr_alt(self->caption, -1, c1, c2);
	}
}

void pi_button_kill(struct pi_button *self)
{
	xfree(self->caption);
}

void pi_button_key(struct pi_button *self, int key)
{
	if (key == ' ' || key == '\n') {
		self->parent->f->handle_cc(self->parent, self->cc);
		((struct pi_window*)self->parent)->text_res = self->text_res;
	} else
		pi_object_key((struct pi_object*)self, key);
}

const char *pi_button_fetch(struct pi_button *self)
{
	return pi_is_active((struct pi_object*)self) ? "yes" : "no";
}

static struct pi_funcs button_funcs = {
	1,
	(pi_handler_void)pi_button_draw,
	(pi_handler_int)pi_object_cc,
	(pi_handler_int)pi_button_key,
	(pi_handler_void)pi_button_kill,
	(pi_handler_rstring)pi_button_fetch,
};

struct pi_button *pi_new_button(int size)
{
	struct pi_button *self;

	if (size == 0)
		size = sizeof(struct pi_button);
	self = (struct pi_button*)pi_new_object(size);

	self->f = &button_funcs;

	return self;
}

struct pi_button *pi_add_button(struct pi_window *par, int x, int y, 
				const char *s, int cc)
{
	struct pi_button *p;

	p = pi_new_button(0);
	pi_setpos((struct pi_object*)p, x, y, pi_strlen_alt(s) + 4, 1);
	pi_setstr(&p->caption, s);
	p->cc = cc;
	pi_add_child((struct pi_object*)par, (struct pi_object*)p);

	return p;
}
