/*
    Tucnak - VHF contest log
    Copyright (C) 2012-2014 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include "button.h"
#include "kbd.h"
#include "tsdl.h"


struct button *init_button(
#ifdef Z_HAVE_SDL
        SDL_Surface *screen, 
#endif
        int x, int y, void (*fn)(void *), void *data){
    struct button *b = g_new0(struct button, 1);
	b->x = x;
	b->y = y;
	b->fn = fn;
	b->data = data;
    return b;
}

void free_button(struct button *b){
#ifdef Z_HAVE_SDL
	if (b->surface) SDL_FreeSurface(b->surface);
#endif    
	g_free(b->text);
	g_free(b);
}

void buttons_clear(GPtrArray *buttons){
	int i;

	for (i = buttons->len - 1; i >= 0; i--){
		struct button *b = (struct button *)g_ptr_array_index(buttons, i);
		free_button(b);
		g_ptr_array_remove_index(buttons, i);
	}
}

#ifdef Z_HAVE_SDL
void buttons_redraw(GPtrArray *buttons, SDL_Surface *dst){
	int i;
	for (i = 0; i < buttons->len; i++){
		struct button *b = (struct button *)g_ptr_array_index(buttons, i);
		button_draw(b, dst);
	}
}

int buttons_mouse(GPtrArray *buttons, int mb, int mx, int my){
	int i;
	for (i = 0; i < buttons->len; i++){
		struct button *b = (struct button *)g_ptr_array_index(buttons, i);
		if ((mb & B_CLICK) == 0) continue;
		if (mx < b->x || mx >= b->x + b->w) continue;
		if (my < b->y || my >= b->y + b->h) continue;
		if (b->fn == NULL) continue;
		b->fn(b->data);
		return 1;
	}
	return 0;
}

void button_draw(struct button *b, SDL_Surface *dst){
	SDL_Rect dr;

	dr.x = b->x;
	dr.y = b->y;
	dr.w = b->w;
	dr.h = b->h;
		
	if (b->surface){
		SDL_BlitSurface(b->surface, NULL, dst, NULL);
	}else{
		SDL_FillRect(dst, &dr, b->bcolor);
		z_rect2(dst, &dr, b->fcolor);
		zsdl_printf(dst, b->x + b->w / 2, b->y + b->h / 2, b->fcolor, 0, ZFONT_TRANSP | ZFONT_CENTERX | ZFONT_CENTERY, "%s", b->text);
	}
}

void button_bitmap(struct button *b, SDL_Surface *surface){
	b->surface = surface;
	b->w = surface->w;
	b->h = surface->h;
}

#endif



void button_text(struct button *b, int font_h, int fcolor, int bcolor, char *text){
	b->font_h = font_h;
	b->fcolor = fcolor;
	b->bcolor= bcolor;
	g_free(b->text);
	b->text = g_strdup(text);
	b->h = font_h;
#ifdef Z_HAVE_SDL
	b->w = zsdl_h2w(font_h) * strlen(b->text);
#endif
}

void button_free(struct button *b){
#ifdef Z_HAVE_SDL
	if (b->surface) SDL_FreeSurface(b->surface);
	g_free(b->text);
    g_free(b);
#endif
}

