#include "Service.h"
#include "item.h"
#include <algorithm>


Service::Service(Repository& repository) : _repository{repository} {

}

void Service::add(std::string name, std::string category, int current_price) {
    Item item(name, category, current_price);
    this->_repository.add_item(item);
    this->notify();
}

void Service::bid(std::string name, int bid, int id, std::string date) {
    Item& item = this->_repository.find_item(name);
    std::tuple <int, std::string, int> bid_tuple(id, date, bid);
    item.add_offer(bid_tuple);
    item.price(bid);
    this->notify();

}

std::vector<Item> Service::get_items() {
    return this->_repository.items();
}

Item& Service::find_item(std::string name) {
    return this->_repository.find_item(name);
}

void Service::attach(Observer* observer) {
    this->_observers.push_back(observer);
}

void Service::detach(Observer* observer) {
    this->_observers.erase(std::remove(this->_observers.begin(), this->_observers.end(), observer), this->_observers.end());
}

void Service::notify() {
    for (auto observer : this->_observers) {
        observer->update();
    }
}