/*
 * 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 "thirdparty/ini/src/ini.h"

#include "config.h"
#include "util.h"


ConfigT __configData;

static char *_configName = NULL;


void configShutdown(void) {
	FILE *out = NULL;

	out = fopen(_configName, "w");
	if (out) {
		fprintf(out,
			"[VIDEO]\n"
			"WIDTH=%d\n"
			"HEIGHT=%d\n"
			"DEPTH=%d\n\n"
			"[SERIAL]\n"
			"COM=%d\n\n"
			"[SERVER]\n"
			"HOST=%s\n"
			"PORT=%d\n\n"
			"[USER]\n"
			"NAME=%s\n",
			__configData.videoWidth, __configData.videoHeight, __configData.videoDepth,
			__configData.serialCom,
			__configData.serverHost, __configData.serverPort,
			__configData.userName
		);
		fclose(out);
	}

	free(__configData.serverHost);
	__configData.serverHost = NULL;

	free(__configData.userName);
	__configData.userName = NULL;

	free(_configName);
	_configName = NULL;
}


void configStartup(char *file) {
	ini_t *ini = NULL;

	// We need this later.
	_configName = utilAppNameWithNewExtensionGet(file, "ini");

	// Numeric Defaults.
	__configData.videoWidth  = 800;
	__configData.videoHeight = 600;
	__configData.videoDepth  = 16;
	__configData.serialCom   = 0;
	__configData.serverPort  = 16550;

	// Load from disk if available.
	ini = ini_load(_configName);
	if (ini) {
		ini_sget(ini, "VIDEO",  "WIDTH",  "%d", &__configData.videoWidth);
		ini_sget(ini, "VIDEO",  "HEIGHT", "%d", &__configData.videoHeight);
		ini_sget(ini, "VIDEO",  "DEPTH",  "%d", &__configData.videoDepth);
		ini_sget(ini, "SERIAL", "COM",    "%d", &__configData.serialCom);
		__configData.serverHost = strdup(ini_get(ini, "SERVER", "HOST"));
		ini_sget(ini, "SERVER", "PORT",   "%d", &__configData.serverPort);
		__configData.userName = strdup(ini_get(ini, "USER", "NAME"));
		ini_free(ini);
	}

	// String defaults.
	if (!__configData.serverHost) __configData.serverHost  = strdup("kanga.world");
	if (!__configData.userName)   __configData.userName    = strdup("New User");
}
