#include "../../repository/FileRepository.h"
#include "../../domain/trench.h"
#include "user_controller.h"
#include <stdio.h>
#include <vector>

UserController::UserController(std::shared_ptr<FileRepository> repo,std::shared_ptr<FileRepository> shoppingRepo) {
    this->_repo = repo;
    this->_shoppingRepository = shoppingRepo;
}

UserController::~UserController() {

}

void UserController::addProductToShoppingList(Trench trench) {
    int index = this->_shoppingRepository->get(trench);
    int repo_index = this->_repo->get(trench);
    if(index==-1) {
        Trench trenchCopy = trench;
        trenchCopy.quantity(1);
        this->_shoppingRepository->add(trenchCopy);
        trench.quantity(trench.quantity()-1);
        (*this->_repo)[repo_index].quantity((*this->_repo)[repo_index].quantity()-1);
        return;
    }
    trench.quantity(trench.quantity()-1);
    this->_shoppingRepository->update(index,trench.price(),(*this->_shoppingRepository)[index].quantity()+1);
    (*this->_repo)[repo_index].quantity((*this->_repo)[repo_index].quantity()-1);

}


int UserController::shoppingListTotal() {
    int total = 0;
    for(Trench i : *this->_shoppingRepository) {
        total+=i.quantity()*i.price();
    }
    return total;
}


std::vector<Trench> UserController::getTrenchCarousel(int size) {
    std::vector<Trench> trenchCarousel;
    for(Trench i : *this->_repo){
        if((size == -1||i.size()==size) && i.quantity()>0){
            Trench copy = i;
            trenchCarousel.push_back(copy);
        }
    }
    return trenchCarousel;
}

void UserController::openShoppingList() {
    this->_shoppingRepository->open();
}
