/* Bob and CJ */

/* Multi-lang2 module

Notes:
All function in here WILL change the current config file!
Currently only supports UTF-8 and ASCII

*/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "allegro.h"
#include "log.h"

#include "multilang2.h"

#define LANGUAGE_FILE "data/language.ini"
#define N_SENTENCES   150
#define SENTENCE_SIZE 260

const char *languages[N_LANGUAGES] = {
	"English", "French", "Spanish"
};

char *language_buf[N_SENTENCES];


static char *current_language = NULL;

int install_multilang(const char *language) {

	int avail = 0, i;
	static int language_installed = 0;
	int lang_switch = 0;
	char *lang;

	if (current_language == NULL)
		memset(language_buf, 0, sizeof(char*) * N_SENTENCES);

	lang = malloc(ustrsizez(language) + ucwidth('[') + ucwidth(']'));
    if (!lang) return -1;
	sprintf(lang, "[%s]", language);

	set_config_file(LANGUAGE_FILE);
	avail = get_config_int(lang, "Available", 0);

	if (!avail) {
		free(lang);
		return -1;
	}


	if (current_language) {
		lang_switch = 1;
		free(current_language);
	}
	current_language = lang;

	if (!language_installed)
		atexit(remove_language);

	language_installed = 1;

	/* Add code to switch languages */
	if (lang_switch) {
		char *old_lang = malloc(sizeof(char) * N_SENTENCES * SENTENCE_SIZE);

		if (!old_lang)
			return 0;

		memcpy(old_lang, language_buf[0], sizeof(char) * N_SENTENCES * SENTENCE_SIZE);
		memset(language_buf[0], 0, sizeof(char) * N_SENTENCES * SENTENCE_SIZE);

		for (i = 0; i < N_SENTENCES; i++) {
			char *text = old_lang + i * SENTENCE_SIZE;
			if (ugetc(text) != 0) {
				char *temp = ustrstr(text, "=");
				*((int*)temp) = 0;
				usprintf(language_buf[i], "%s=%s", text, translate(text));
			}
		}
	}

	return 0;
}

const char *translate(const char *text) {

	int i;
	const char *ret;
	set_config_file(LANGUAGE_FILE);
	ret = get_config_string(current_language, text, empty_string);

	if (!language_buf[0]) {
		language_buf[0] = malloc(sizeof(char) * N_SENTENCES * SENTENCE_SIZE);
        if (!language_buf[0]) exit(37);
		memset(language_buf[0], 0, sizeof(char) * N_SENTENCES * SENTENCE_SIZE);

		for (i = 1; i < N_SENTENCES; i++)
			language_buf[i] = language_buf[0] + i * SENTENCE_SIZE;
	}

	for (i = 0; i < N_SENTENCES; i++) {
		if (ustrncmp(text, language_buf[i], MIN(ustrlen(text), 255)) == 0) {
			ret = ustrstr(language_buf[i], "=");
			ret += uwidth(ret);
			return ret;
		}
		else if (!ugetc(language_buf[i])) {
			usprintf(language_buf[i], "%s=%s", text, ret);

			ret = ustrstr(language_buf[i], "=");
			ret += uwidth(ret);
			
			return ret;
		}
	}

	return NULL;
}


void remove_language(void) {

	if (current_language)
		free(current_language);
	current_language = NULL;

	if (language_buf[0])
		free(language_buf[0]);

	return;
}
