#include "QuestionRepo.h"
#include <stdexcept>

QuestionRepo::QuestionRepo(std::string file_name)
{
    this->_file_name = file_name;
    this->read_from_file();
}

QuestionRepo::~QuestionRepo()
{
    this->write_to_file();
}

void QuestionRepo::add(Question q)
{
    for(auto& question : this->_questions)
        if(question.id() == q.id())
            throw std::runtime_error("Question already exists!");
    this->_questions.push_back(q);
}

std::vector<Question> QuestionRepo::get_all()
{
    return this->_questions;
}

int QuestionRepo::size()
{
    return this->_questions.size();
}

void QuestionRepo::read_from_file()
{
    std::ifstream file(this->_file_name);
    if(!file.is_open())
        throw std::runtime_error("File could not be opened!");
    std::string line;
    while(std::getline(file, line) && !line.empty())
    {
        Question q;
        line >> q;
        this->_questions.push_back(q);
    }
    file.close();
}

void QuestionRepo::write_to_file()
{
    std::ofstream file(this->_file_name);
    if(!file.is_open())
        throw std::runtime_error("File could not be opened!");
    for(auto& question : this->_questions)
        file << question;
    file.close();
}