#include "WordManager.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <random>

WordManager::WordManager(int difficulty) : difficultyLevel(difficulty) {
    std::ifstream file("words.txt");
    if (!file.is_open()) {
        std::cerr << "Ошибка открытия файла words.txt\n";
        exit(EXIT_FAILURE);
    }
    std::vector<std::string> words;
    std::string word;
    while (std::getline(file, word)) {
        if (difficultyLevel == 1 && word.length() <= 5) {
            words.push_back(word);
        } else if (difficultyLevel == 2 && word.length() > 5 && word.length() <= 8) {
            words.push_back(word);
        } else if (difficultyLevel == 3 && word.length() > 8) {
            words.push_back(word);
        }
    }
    if (words.empty()) {
        std::cerr << "Нет слов для выбранного уровня сложности\n";
        exit(EXIT_FAILURE);
    }
    std::random_device rd;
    std::mt19937 gen(rd());
    std::shuffle(words.begin(), words.end(), gen);
    secretWord = words.front();
    displayedWord = std::string(secretWord.length(), '_');
}

bool WordManager::checkLetter(char letter) {
    bool found = false;
    for (size_t i = 0; i < secretWord.size(); ++i) {
        if (secretWord[i] == letter) {
            displayedWord[i] = letter;
            found = true;
        }
    }
    guessedLetters.insert(letter);
    return found;
}

std::string WordManager::getDisplayedWord() const {
    return displayedWord;
}

bool WordManager::isWordGuessed() const {
    return displayedWord == secretWord;
}

void WordManager::setDifficulty(int level) {
    difficultyLevel = level;
}
