//
// Created by sasha on 01.12.2025.
//

#include "record_store.h"

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

#include <SDL3/SDL.h>

RecordStore::RecordStore() {

}

void RecordStore::save(const std::string &type, int turn, int time) {
    std::vector<RECORD> records = load(type);

    bool isWriteRecord = false;

    SDL_Log("RecordStore::save: %i %i",turn, time);

    char *p = SDL_GetPrefPath("dansoft","puzzle15");
    std::string filename = std::format("{}/record_{}.txt",p,type);
    SDL_free(p);

    std::ofstream out;
    out.open(filename);
    for (int i=0;i<5;i++){
        if (records.size()>i){
            if (time<records.at(i).time and !isWriteRecord){
                out << turn << " " << time << "\n";
                isWriteRecord=true;
            }
            out << records.at(i).turn << " " << records.at(i).time << "\n";
        }
        if (!isWriteRecord){
            out << turn << " " << time << "\n";
            isWriteRecord=true;
        }
    }

    out.close();
}

std::vector<RECORD> RecordStore::load(const std::string &type) {
    std::vector<RECORD> result;

    char *p = SDL_GetPrefPath("dansoft","puzzle15");
    std::string filename = std::format("{}/record_{}.txt",p,type);
    SDL_free(p);

    std::ifstream in;
    in.open(filename);
    if (in.is_open()) {
        std::string line;
        while (std::getline(in, line)) {
            std::vector<std::string> tokens = parseString(line,' ');
            result.push_back({std::stoi(tokens.at(0)),std::stoi(tokens.at(1))});
        }
    }else{
        SDL_Log("error open file %s: %s",filename.c_str(), strerror(errno));
    }
    in.close();


    return result;
}

bool RecordStore::isRecord(const std::string &type, int turn, int time) {
    std::vector<RECORD> records = load(type);

    if (records.empty()) return true;

    for (RECORD &rec : records){
        if (time<rec.time){
            return true;
        }
    }

    return false;
}

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