//
// Created by sasha on 08.12.2025.
//

#include "locale.h"

#include <algorithm>
#include <format>
#include <sstream>
#include <fstream>

#include <SDL3/SDL.h>

#include "global_params.h"


Locale* Locale::instance = nullptr;


Locale::Locale() {

}

bool Locale::init(std::string locale) {
    std::transform(locale.begin(), locale.end(), locale.begin(), ::tolower);
    this->locale = locale;

    std::string asset_path = GlobalParams::assetPath();

    std::string filename = std::format("{}locales/messages_{}.lng",asset_path,locale);

    size_t size;
    char* data = (char*)SDL_LoadFile(filename.c_str(), &size);
    if (!data) {
        printf("error load file: %s\n", SDL_GetError());
        return false;
    }

    char* line_start = data;
    size_t line_num = 0;
    std::string line;
    for (size_t i = 0; i < size; i++) {
        if (data[i] == '\n' || data[i] == '\0') {
            line = std::string(line_start,i-line_num);
            std::vector<std::string> tokens = parseString(line, '=');
            if (tokens.size() != 2) continue;
            translate[tokens.at(0)] = tokens.at(1);
            line_num=i+1;
            line_start = data + i+1;
        }
    }
    free(data);

    return true;
}

std::string Locale::tr(const std::string &string) {
    if (translate.contains(string)){
        return translate[string];
    }
    return string;
}


// разделение строки через разделитель
std::vector<std::string> Locale::parseString(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;

    std::stringstream ss(str);
    std::string token;
    while (std::getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }

    return tokens;
}