shadow-over-bishkek001/src/Localization.cpp
2026-07-07 11:24:21 +03:00

72 lines
2.0 KiB
C++

#include "Localization.h"
#include "external/nlohmann/json.hpp"
#include "utils/Utils.h"
#include <iostream>
namespace ZL {
Language g_currentLanguage = Language::Russian;
std::string languageToCode(Language lang) {
switch (lang) {
case Language::English: return "en";
case Language::Russian:
default: return "ru";
}
}
Language languageFromCode(const std::string& code) {
if (code == "en") return Language::English;
return Language::Russian;
}
std::string localizedConfigPath(const std::string& basePath, Language lang) {
static const std::string marker = "/config/";
const size_t pos = basePath.find(marker);
if (pos == std::string::npos) return basePath;
return basePath.substr(0, pos) + "/config_" + languageToCode(lang) + "/" + basePath.substr(pos + marker.size());
}
std::string readLocalizedConfigFile(const std::string& basePath, const std::string& zipFile) {
const std::string localizedPath = localizedConfigPath(basePath, g_currentLanguage);
if (localizedPath != basePath) {
std::string content;
if (zipFile.empty()) {
content = readTextFile(localizedPath);
} else {
try {
const auto buf = readFileFromZIP(localizedPath, zipFile);
content.assign(buf.begin(), buf.end());
} catch (const std::exception&) {
content.clear();
}
}
if (!content.empty()) return content;
}
if (zipFile.empty()) return readTextFile(basePath);
try {
const auto buf = readFileFromZIP(basePath, zipFile);
return std::string(buf.begin(), buf.end());
} catch (const std::exception&) {
return "";
}
}
void loadLanguageSetting() {
const std::string content = readTextFile("settings.json");
if (content.empty()) return;
try {
const nlohmann::json root = nlohmann::json::parse(content);
if (root.contains("language")) {
g_currentLanguage = languageFromCode(root["language"].get<std::string>());
}
} catch (const std::exception& e) {
std::cerr << "[settings] Failed to parse settings.json: " << e.what() << std::endl;
}
}
} // namespace ZL