/*
 * 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 "frame.h"


static void frameDel(WidgetT **widget);
static void framePaint(WidgetT *widget, uint8_t enabled, RectT pos);


static void frameDel(WidgetT **widget) {
	FrameT *f = (FrameT *)*widget;

	if (f->title) free(f->title);
}


WidgetT *frameInit(WidgetT *widget, char *title) {
	FrameT *f = (FrameT *)widget;

	f->base.delMethod        = frameDel;
	f->base.paintMethod      = framePaint;
	f->title                 = NULL;

	frameTitleSet(f, title);

	return widget;
}


FrameT *frameNew(uint16_t x, uint16_t y, uint16_t w, uint16_t h, char *title) {
	FrameT  *frame  = (FrameT *)malloc(sizeof(FrameT));
	WidgetT *widget = NULL;

	if (!frame) return NULL;

	widget = widgetInit(W(frame), MAGIC_FRAME, x, y, w, h, 4, 20, 4, 4);
	if (!widget) {
		free(frame);
		return NULL;
	}

	frame = (FrameT *)frameInit((WidgetT *)frame, title);

	return frame;
}


static void framePaint(WidgetT *widget, uint8_t enabled, RectT pos) {
	FrameT   *f = (FrameT *)widget;

	// Draw frame.
	surfaceHighlightFrameDraw(pos.x, pos.y + (fontHeightGet(_guiFont) * 0.5), pos.x + pos.w, pos.y + pos.h, _guiColor[COLOR_FRAME_SHADOW], _guiColor[COLOR_FRAME_HIGHLIGHT]);

	// Draw title.
	fontRender(_guiFont, f->title, _guiColor[COLOR_FRAME_TEXT], _guiColor[COLOR_WINDOW_BACKGROUND], pos.x + 10, pos.y);
}


void frameTitleSet(FrameT *frame, char *title) {
	if (frame->title) free(frame->title);
	frame->title = (char *)malloc(strlen(title) + 3);
	frame->title[0] = ' ';
	frame->title[1] = 0;
	strcat(frame->title, title);
	strcat(frame->title, " ");
	GUI_SET_FLAG((WidgetT *)frame, WIDGET_FLAG_DIRTY);
}
