/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * 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 3 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, see <https://www.gnu.org/licenses/>.
 *
 */


#include "picture.h"


static void pictureDel(WidgetT **widget);
static void pictureMouseEvent(WidgetT *widget, MouseT *mouse, uint16_t x, uint16_t y, uint8_t event);
static void picturePaint(WidgetT *widget, uint8_t enabled, RectT pos);


void pictureClickHandlerSet(PictureT *picture, widgetCallback callback) {
	picture->clicked = callback;
}


static void pictureDel(WidgetT **widget) {
	PictureT *p = (PictureT *)*widget;

	if (p->image) imageUnload(&p->image);
	if (p->filename) free(p->filename);
}


WidgetT *pictureInit(WidgetT *widget, char *filename) {
	PictureT *l = (PictureT *)widget;

	l->base.delMethod        = pictureDel;
	l->base.paintMethod      = picturePaint;
	l->base.mouseEventMethod = pictureMouseEvent;
	l->filename              = strdup(filename);
	l->clicked               = NULL;

	l->image = imageLoad(l->filename);
	if (!l->image) {
		free(l->filename);
		return NULL;
	}

	return widget;
}


static void pictureMouseEvent(WidgetT *widget, MouseT *mouse, uint16_t x, uint16_t y, uint8_t event) {
	PictureT *p = (PictureT *)widget;

	(void)x;
	(void)y;
	(void)mouse;

	// Fire callback on mouse up.
	if (event == MOUSE_EVENT_LEFT_UP) {
		if (p->clicked) guiPendingEventAdd(widget, p->clicked);
	}
}


PictureT *pictureNew(uint16_t x, uint16_t y, char *filename) {
	PictureT *picture = (PictureT *)malloc(sizeof(PictureT));
	WidgetT  *widget  = NULL;
	uint16_t  w;
	uint16_t  h;

	if (!picture) return NULL;

	if (!imageInfoGet(filename, &w, &h)) {
		free(picture);
		return NULL;
	}

	widget = widgetInit(W(picture), MAGIC_PICTURE, x, y, w, h, 0, 0, 0, 0);
	if (!widget) {
		free(picture);
		return NULL;
	}

	picture = (PictureT *)pictureInit((WidgetT *)picture, filename);
	if (!picture) {
		free(picture);
		return NULL;
	}

	return picture;
}


static void picturePaint(WidgetT *widget, uint8_t enabled, RectT pos) {
	PictureT *p = (PictureT *)widget;

	imageRender(p->image, pos.x, pos.y);
}
