/*
 * 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 <mysql.h>
#include <pthread.h>

#include "database.h"


#define STATEMENT_MAX  2048


static MYSQL          *_sql = NULL;
static char            _statement[STATEMENT_MAX];
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;


uint8_t dbConnect(char *host, uint16_t port, char *database, char *user, char *password) {
	uint8_t reconnect = 1;

	if (_sql == NULL) {
		_sql = mysql_init(NULL);
		mysql_options(_sql, MYSQL_OPT_RECONNECT, (const void *)&reconnect);
		if (mysql_real_connect(_sql, host, user, password, database, port, NULL, 0) == NULL) {
			logWrite("dbConnect:  %s\n", mysql_error(_sql));
			return FAIL;
		}
		if (pthread_mutex_init(&_mutex, NULL)) {
			logWrite("dbConnect:  SQL mutex creation failed.\n");
			return FAIL;
		}
		return SUCCESS;
	}
	return FAIL;
}


uint8_t dbDisconnect(void) {
	if (_sql) {
		 mysql_close(_sql);
		 _sql = NULL;
		 pthread_mutex_destroy(&_mutex);
		 return SUCCESS;
	}

	return FAIL;
}


uint8_t dbSettingsValueGet(char *key, int32_t *value) {
	char      *p      = _statement;
	MYSQL_RES *result = NULL;
	MYSQL_ROW  row;
	int        count;

	pthread_mutex_lock(&_mutex);

	if (!_sql) {
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	p += sprintf(p, "SELECT data FROM config where NAME='");
	p += mysql_real_escape_string(_sql, p, key, strlen(key));
	p += sprintf(p, "'");
	if (mysql_real_query(_sql, _statement, p - _statement) != 0) {
		logWrite("dbConfigValueGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	result = mysql_store_result(_sql);
	count = mysql_num_rows(result);
	if (count != 1) {
		logWrite("dbConfigValueGet:  Too many rows returned:  %d.\n", count);
		mysql_free_result(result);
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	if ((row = mysql_fetch_row(result)) == NULL) {
		logWrite("dbConfigValueGet:  %s\n", mysql_error(_sql));
		pthread_mutex_unlock(&_mutex);
		return FAIL;
	}

	*value = atoi(row[0]);

	mysql_free_result(result);

	pthread_mutex_unlock(&_mutex);

	return SUCCESS;
}
