#include "MemoryRepository.h"
#include "../exceptions/exceptions.h"

MemoryRepository::MemoryRepository(){
    
}
MemoryRepository::~MemoryRepository(){

}
void MemoryRepository::add(Trench trench){
    if(this->get(trench)!=-1)
        throw RepoException("Trench already exists");
    this->_data.push_back(trench);

}
void MemoryRepository::remove(Trench trench){
    int index = this->get(trench);
    if(index==-1)
        throw RepoException("Trench does not exists");
    this->remove(index);
}
void MemoryRepository::remove(int index){
    if(index<0 || index > (int)(this->_data.size())-1)
        throw RepoException("Index out of bounds");
    this->_data.erase(this->_data.begin()+index);
}

int MemoryRepository::get(Trench trench){
    for(int i=0;i<(int)(this->_data.size());i++){
        if(trench == this->_data[i])
            return i;
    }
    return -1;
}

Trench& MemoryRepository::operator[](int index){
    if(index<0 || index > (int)(this->_data.size())-1)
        throw RepoException("Index out of bounds");
    return this->_data[index];
}
void MemoryRepository::update(int index, int price, int quantity){
    if(index<0 || index > (int)(this->_data.size())-1)
        throw RepoException("Index out of bounds");
    Trench& trench = this->_data[index];
    if(price!=-1 && price<=0)
        throw RepoException("Invalid price");
    if(quantity!=-1 && quantity<0)
        throw RepoException("Invalid quantity");
    if(price>0)
        trench.price(price);
    if(quantity>=0)
        trench.quantity(quantity);
}

int MemoryRepository::size(){
    return this->_data.size();
}

std::vector<Trench>::iterator MemoryRepository::begin(){
    return this->_data.begin();
}
std::vector<Trench>::iterator MemoryRepository::end(){
    return this->_data.end();
}