#include "repo.h"
#include <stdexcept>
#include <fstream>

Repository::Repository()
{
    this->read_from_file();
}

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

std::vector<User> Repository::users()
{
    return this->_users;
}

std::vector<Item> Repository::items()
{
    return this->_items;
}

void Repository::add_item(Item item)
{
    for(auto it : this->_items){
        if(it.name() == item.name()){
            throw std::runtime_error("Item already exists");
        }
    }
    this->_items.push_back(item);
}

Item& Repository::find_item(std::string name)
{
    for(auto& it : this->_items){
        if(it.name() == name){
            return it;
        }
    }
    throw std::runtime_error("Item not found");
}

void Repository::read_from_file()
{
    std::ifstream f("items.txt");
    std::string name, category;
    int price;
    std::string line;
    std::string buf;
    int user_id;
    std::string date;
    int offer_price;
    while(std::getline(f,line) || line != ""){
        buf=line.substr(0, line.find("|"));
        name = buf;
        line.erase(0, line.find("|")+1);
        buf=line.substr(0, line.find("|"));
        category = buf;
        line.erase(0, line.find("|")+1);
        buf=line.substr(0, line.find("|"));
        price = std::stoi(buf);
        line.erase(0, line.find("|")+1);
        std::vector<std::tuple<int,std::string,int>> offers;
        while(line != ""){
            buf=line.substr(0, line.find(","));
            user_id = std::stoi(buf);
            line.erase(0, line.find(",")+1);
            buf=line.substr(0, line.find(","));
            date = buf;
            line.erase(0, line.find(",")+1);
            buf=line.substr(0, line.find(","));
            offer_price = std::stoi(buf);
            line.erase(0, line.find(";")+1);
            offers.push_back(std::make_tuple(user_id, date, offer_price));
        }
        this->_items.push_back(Item(name, category, price, offers));
    }
    std::string type;
    int id;
    std::ifstream g("users.txt");
    while(std::getline(g,line) || line != ""){
        buf=line.substr(0, line.find("|"));
        id = std::stoi(buf);
        line.erase(0, line.find("|")+1);
        buf=line.substr(0, line.find("|"));
        name = buf;
        line.erase(0, line.find("|")+1);
        buf=line.substr(0, line.find("|"));
        type = buf;
        line.erase(0, line.find("|")+1);
        this->_users.push_back(User(name, id, type));
    }
    f.close();
    g.close();
}

void Repository::write_to_file()
{
    std::ofstream f("items.txt");
    for(auto it : this->_items){
        f<<it.name()<<"|"<<it.category()<<"|"<<it.price()<<"|";
        for(auto it2 : it.offers()){
            f<<std::get<0>(it2)<<","<<std::get<1>(it2)<<","<<std::get<2>(it2)<<";";
        }
        f<<"\n";
    }
    f.close();
}

