//
// Created by sasha on 02.12.2025.
//

#include "config_storage.h"

#include <iostream>
#include <fstream>
#include <format>
#include <sstream>

#include <SDL3/SDL.h>


ConfigStorage::ConfigStorage() {
    char *p = SDL_GetPrefPath("dansoft","puzzle15");
    filename = std::format("{}/config.cfg",p);
    SDL_free(p);

}

bool ConfigStorage::statusSound() {

    std::ifstream in;
    in.open(filename);
    if (in.is_open()) {
        std::string line;
        std::getline(in, line);
        std::vector<std::string> tokens = parseString(line,' ');

        // звук
        if (tokens.size()>0 and tokens.at(0)=="0") return false;
    }else{
        SDL_Log("error open file %s: %s",filename.c_str(), strerror(errno));
    }
    in.close();

    return true;
}

void ConfigStorage::setStatusSound(bool value) {
    int sound = value ? 1:0;

    std::ofstream out;
    out.open(filename);
    out << sound << "\n";
    out.close();
}

// разделение строки через разделитель
std::vector<std::string> ConfigStorage::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;
}