#include "Index.h"
#include <fstream>
#include <sstream>
#include <format>


void Index::process(const std::string& file) {
    std::ifstream file_stream;
    file_stream.open(file);
    if (!file_stream.good()) {
        throw std::format(OPEN_FILE_EXCEPTION, file);
    }
    std::string line;
    while (std::getline(file_stream, line)) {
        std::istringstream line_stream(line);
        std::string term;
        while (std::getline(line_stream, term, WORD_SEPARATOR)) {
            if (term.empty()) continue;
            if (term[0] == SPECIAL_CHAR) {
                throw std::format(INVALID_TERM_EXCEPTION, term);
            }
            if (index_map_.contains(term)) {
                index_map_[std::move(term)].insert(next_identifier_);
            } else {
                index_map_[std::move(term)] = {next_identifier_};
            }
        }
    }
    ++next_identifier_;
    file_stream.close();
}

void Index::dump(std::ostream& stream) const {
    for (const auto& [term, ids_set] : index_map_) {
        stream << term << " -> { ";
        for (auto it = ids_set.begin(); it != ids_set.end();) {
            stream << *it;
            if (++it != ids_set.end()) {
                stream << ", ";
            }
        }
        stream << " }" << std::endl;
    }
}

std::set<Identifier> Index::search(const std::string& term) const {
    if (auto search = index_map_.find(term); search != index_map_.end()) {
        return search->second;
    } else {
        return {};
    }
}
