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

#include "taglist.h"
#include "msgbox.h"
#include "window.h"
#include "picture.h"
#include "button.h"
#include "frame.h"
#include "listbox.h"
#include "textbox.h"
#include "timer.h"

#include "db.h"
#include "network.h"
#include "util.h"


static WindowT     *_winBrowser        = NULL;
static TimerT      *_timSearchUpdate   = NULL;

static ButtonT     *_btnSearchTab      = NULL;
static FrameT      *_fraSearch         = NULL;
static TextboxT    *_txtSearch         = NULL;
static ListboxT    *_lstResults        = NULL;

static ButtonT     *_btnDescriptionTab = NULL;
static FrameT      *_fraDescription    = NULL;
static PictureT    *_picBanner         = NULL;
static ListboxT    *_lstDescription    = NULL;

static ButtonT     *_btnScreensTab     = NULL;
static FrameT      *_fraScreens        = NULL;
static PictureT    *_picThumb1         = NULL;
static PictureT    *_picThumb2         = NULL;
static PictureT    *_picThumb3         = NULL;
static PictureT    *_picThumb4         = NULL;
static PictureT    *_picThumb5         = NULL;
static PictureT    *_picThumb6         = NULL;

static ButtonT     *_btnBoxTab         = NULL;
static FrameT      *_fraBox            = NULL;
static PictureT    *_picBox1           = NULL;
static PictureT    *_picBox2           = NULL;

static ButtonT     *_btnInfoTab        = NULL;
static FrameT      *_fraInfo           = NULL;
static ListboxT    *_lstInfo           = NULL;

static uint8_t      _channel           = 0;
static char        *_lastSearchText    = NULL;


static void browserHide(void);
static void btnTabClick(WidgetT *widget);
static void packetHandler(PacketDecodeDataT *packet);
static void timSearchUpdate(WidgetT *widget);


static void browserHide(void) {
	timerStop(_timSearchUpdate);
	DEL(_lastSearchText);
	netChannelRelease(_channel);
	guiDelete(D(_winBrowser));
}


void browserShow(void) {

	//char **lines = NULL;

	TagItemT uiBrowser[] = {
		T_START,
			T_WINDOW, O(_winBrowser),
				T_TITLE, P("Game Browser"),
				T_WIDTH, 525, T_HEIGHT, 323,

				// SEARCH
				T_BUTTON, O(_btnSearchTab),
					T_X, 5, T_Y, 5,
					T_TITLE, P("Search"),
					T_CLICK, P(btnTabClick),
				T_BUTTON, T_DONE,
				T_FRAME, O(_fraSearch),
					T_X, 5, T_Y, 32,
					T_WIDTH, 500, T_HEIGHT, 250,
					T_TITLE, P("Search"),

					T_TEXTBOX, O(_txtSearch),
						T_TITLE, P("Game, Publisher, or Developer:"),
						T_X, 5, T_Y, 3,
						T_WIDTH, 490,
						T_LENGTH, 255,
					T_TEXTBOX, T_DONE,
					T_LISTBOX, O(_lstResults),
						T_X, 1, T_Y, 35,
						T_WIDTH, 493, T_HEIGHT, 190,  // Works out to 57 characters wide, 13 high.
					T_LISTBOX, T_DONE,

				T_FRAME, T_DONE,

				// GAME
				T_BUTTON, O(_btnDescriptionTab),
					T_X, 78, T_Y, 5,
					T_TITLE, P("Game"),
					T_CLICK, P(btnTabClick),
					T_ENABLED, T_FALSE,
				T_BUTTON, T_DONE,
				T_FRAME, O(_fraDescription),
					T_X, 5, T_Y, 32,
					T_WIDTH, 500, T_HEIGHT, 250,
					T_TITLE, P("Description"),
					T_VISIBLE, T_FALSE,

					T_PICTURE, O(_picBanner),
						T_X, 1, // 490PX wide
						T_CACHENAME, P("games:d:descent:banner.png"),  // ***TODO*** This needs a "browser:no-banner.png" image.
					T_PICTURE, T_DONE,
					T_LISTBOX, O(_lstDescription),
						T_X, 1, T_Y, 105,
						T_WIDTH, 493, T_HEIGHT, 124,  // Works out to 57 characters wide, 8 high.
					T_LISTBOX, T_DONE,

				T_FRAME, T_DONE,

				// SCREENSHOTS
				T_BUTTON, O(_btnScreensTab),
					T_X, 135, T_Y, 5,
					T_TITLE, P("Screens"),
					T_CLICK, P(btnTabClick),
					T_ENABLED, T_FALSE,
				T_BUTTON, T_DONE,
				T_FRAME, O(_fraScreens),
					T_X, 5, T_Y, 32,
					T_WIDTH, 500, T_HEIGHT, 250,
					T_TITLE, P("Screenshots"),
					T_VISIBLE, T_FALSE,

						T_PICTURE, O(_picThumb1),  // Thumbs are 160x100
							T_X, 1, T_Y, 5,
							T_CACHENAME, P("browser:no-screen.png"),
						T_PICTURE, T_DONE,
						T_PICTURE, O(_picThumb2),
							T_X, 167, T_Y, 5,
							T_CACHENAME, P("browser:no-screen.png"),
							T_VISIBLE, T_FALSE,
						T_PICTURE, T_DONE,
						T_PICTURE, O(_picThumb3),
							T_X, 333, T_Y, 5,
							T_CACHENAME, P("browser:no-screen.png"),
							T_VISIBLE, T_FALSE,
						T_PICTURE, T_DONE,

						T_PICTURE, O(_picThumb4),
							T_X, 1, T_Y, 116,
							T_CACHENAME, P("browser:no-screen.png"),
							T_VISIBLE, T_FALSE,
						T_PICTURE, T_DONE,
						T_PICTURE, O(_picThumb5),
							T_X, 167, T_Y, 116,
							T_CACHENAME, P("browser:no-screen.png"),
							T_VISIBLE, T_FALSE,
						T_PICTURE, T_DONE,
						T_PICTURE, O(_picThumb6),
							T_X, 333, T_Y, 116,
							T_CACHENAME, P("browser:no-screen.png"),
							T_VISIBLE, T_FALSE,
						T_PICTURE, T_DONE,

				T_FRAME, T_DONE,

				// BOX
				T_BUTTON, O(_btnBoxTab),
					T_X, 216, T_Y, 5,
					T_TITLE, P("Box"),
					T_CLICK, P(btnTabClick),
					T_ENABLED, T_FALSE,
				T_BUTTON, T_DONE,
				T_FRAME, O(_fraBox),
					T_X, 5, T_Y, 32,
					T_WIDTH, 500, T_HEIGHT, 250,
					T_TITLE, P("Packaging"),
					T_VISIBLE, T_FALSE,

						T_PICTURE, O(_picBox1),  // Thumbs are 240x210
							T_X, 1, T_Y, 5,
							T_CACHENAME, P("browser:no-box.png"),
						T_PICTURE, T_DONE,
						T_PICTURE, O(_picBox2),
							T_X, 250, T_Y, 5,
							T_CACHENAME, P("browser:no-box.png"),
							T_VISIBLE, T_FALSE,
						T_PICTURE, T_DONE,

				T_FRAME, T_DONE,

				// INFO
				T_BUTTON, O(_btnInfoTab),
					T_X, 265, T_Y, 5,
					T_TITLE, P("Info"),
					T_CLICK, P(btnTabClick),
					T_ENABLED, T_FALSE,
				T_BUTTON, T_DONE,
				T_FRAME, O(_fraInfo),
					T_X, 5, T_Y, 32,
					T_WIDTH, 500, T_HEIGHT, 250,
					T_TITLE, P("Information"),
					T_VISIBLE, T_FALSE,

					T_LISTBOX, O(_lstInfo),
						T_X, 1, T_Y, 5,
						T_WIDTH, 493, T_HEIGHT, 220,  // Works out to 57 characters wide, 15 high.
					T_LISTBOX, T_DONE,

				T_FRAME, T_DONE,

				T_TIMER, O(_timSearchUpdate),
					T_EVENT, P(timSearchUpdate),
					T_VALUE, 3,
					T_ENABLED, 1,
				T_TIMER, T_DONE,

			T_WINDOW, T_DONE,
		T_END
	};

	tagListRun(uiBrowser);
	guiFocusSet(W(_txtSearch));
	_channel = netChannelGet(packetHandler);

	_lastSearchText = strdup("");

	/*
	guiDebugAreaShow(W(_fraSearch));

	lines = utilWrapText(
		"The Post-Terran Minerals Corporation (PTMC) digs up minerals on all nine planets of the solar system, "
		"employing humans and robots to do its job. Unfortunately, the mining robots are now being controlled by a hacker, "
		"and have taken the human workers hostage. The PTMC has tried to get the robots back under their control, but "
		"communication with the mining stations has been lost. In desperation, the PTMC modifies a Pyro-GX ship for combat "
		"and hires a mercenary, codenamed 'Material Defender', to fly it. The mission is to destroy the infected mines and "
		"rescue human hostages, destroying any hostile robot that gets in the way.", 57);
	while (arrlen(lines) > 0) {
		listboxItemAdd(_lstDescription, lines[0]);
		DEL(lines[0]);
		arrdel(lines, 0);
	}

	listboxItemAdd(_lstResults, "123456789012345678901234567890123456789012345678901234567");
	listboxItemAdd(_lstResults, "2");
	listboxItemAdd(_lstResults, "3");
	listboxItemAdd(_lstResults, "4");
	listboxItemAdd(_lstResults, "5");
	listboxItemAdd(_lstResults, "6");
	listboxItemAdd(_lstResults, "7");
	listboxItemAdd(_lstResults, "8");
	listboxItemAdd(_lstResults, "9");
	listboxItemAdd(_lstResults, "10");
	listboxItemAdd(_lstResults, "11");
	listboxItemAdd(_lstResults, "12");
	listboxItemAdd(_lstResults, "13");
	listboxItemAdd(_lstResults, "14");
	listboxItemAdd(_lstResults, "15");
	listboxItemAdd(_lstResults, "16");
	listboxItemAdd(_lstResults, "17");
	*/
}


static void btnTabClick(WidgetT *widget) {

	widgetVisibleSet(W(_fraBox),         0);
	widgetVisibleSet(W(_fraDescription), 0);
	widgetVisibleSet(W(_fraInfo),        0);
	widgetVisibleSet(W(_fraScreens),     0);
	widgetVisibleSet(W(_fraSearch),      0);

	if (widget == W(_btnBoxTab))         widgetVisibleSet(W(_fraBox),         1);
	if (widget == W(_btnDescriptionTab)) widgetVisibleSet(W(_fraDescription), 1);
	if (widget == W(_btnInfoTab))        widgetVisibleSet(W(_fraInfo),        1);
	if (widget == W(_btnScreensTab))     widgetVisibleSet(W(_fraScreens),     1);
	if (widget == W(_btnSearchTab))      widgetVisibleSet(W(_fraSearch),      1);
}


static void packetHandler(PacketDecodeDataT *packet) {

}


static void timSearchUpdate(WidgetT *widget) {
	char     ***records = NULL;
	char      **fields  = NULL;
	uint16_t    count   = 0;
	char        query[258];   // 255 search characters, two %'s, and the terminating null.

	(void)widget;

	// Are there more than two characters in the search field?
	if (textboxValueGet(_txtSearch) && strlen(textboxValueGet(_txtSearch)) > 2) {
		// Did the search contents change?
		if (strcmp(_lastSearchText, textboxValueGet(_txtSearch))) {
			// Remember what was in the search box.
			DEL(_lastSearchText);
			_lastSearchText = strdup(textboxValueGet(_txtSearch));
			// Clear current search results.
			listboxItemsClear(_lstResults);
			// Execute search.
			snprintf(query, 258, "%%%s%%", _lastSearchText);
			dbQueryMultiple(&records,
				"SELECT title FROM games WHERE "
				"title LIKE ? OR developer LIKE ? OR publisher LIKE ? "
				"ORDER BY title",
				"vvv",
				query,
				query,
				query);
			// Did we get anything?
			if (records) {
				for (count = 0; count < arrlen(records); count++) {
					fields = records[count];
					listboxItemAdd(_lstResults, fields[0]);
				}
				dbResultRelease(&records);
			}
		}
	}
}
