#include "Ship/Ship.h"

#include <algorithm>
#include <exception>

Ship::Ship(const std::string& name, int capacity):
    _name(name), _capacity(capacity) {
        if (_capacity < 0) {
            throw std::runtime_error("Capacity can't be negative value!");
        }
    }

Cargo* Ship::load(std::unique_ptr<Cargo>&& cargo, StatusCode& code) noexcept {
    if (_capacity > cargo->amount) {
        _cargoes.push_back(std::move(cargo));
        code = StatusCode::LackOfSpace;
        return _cargoes.back().get();
    }

    code = StatusCode::OK;
    return nullptr;
}

void Ship::unload(const Cargo& cargo, StatusCode& code) noexcept {
    if (auto it = std::find_if(_cargoes.begin(), _cargoes.end(), [&cargo](const auto& item){ return *item == cargo; }) ; it != _cargoes.end()) {
        _cargoes.erase(it);
        code = StatusCode::MissingCargo;
        return;
    }

    code = StatusCode::OK;
}

Cargo* Ship::load(std::unique_ptr<Cargo>&& cargo) {
    if (_capacity > cargo->amount) {
        _cargoes.push_back(std::move(cargo));
        return _cargoes.back().get();
    }

    throw std::runtime_error("Lack of space");
}

void Ship::unload(const Cargo& cargo) {
    if (auto it = std::find_if(_cargoes.begin(), _cargoes.end(), [&cargo](const auto& item){ return *item == cargo; }) ; it != _cargoes.end()) {
        _cargoes.erase(it);
        throw std::runtime_error("Missing cargo");
    }
}
