#include "basicPipe.h"
#include "plant.h"
#include <render/render.h>
#include <string.h>
#include <resources.h>

namespace game{

basicPipe::basicPipe(const vec2f &pos, const vec2u &size, level *root):entity(pos, size, root)
{
    _placeOnMap();
    _item = 0xFFFFFFFF;
    _amount = 0;
}

void basicPipe::beforeNeighbourDestroyed(entity *ent)
{
    if(basicPipe *p = dynamic_cast<basicPipe*>(ent))
        _connections.remove(p);
}

void basicPipe::onNeighbourCreated(entity *ent)
{
    if(basicPipe *p = dynamic_cast<basicPipe*>(ent))
    {
        _connections.push_back(p);
        p->_connections.push_back(this);
    }

    if(plant *p = dynamic_cast<plant*>(ent))
        p->addPipe(this);
}

void basicPipe::update()
{
    float filled = getFilledSpace();

    for(basicPipe *i: _connections)
    {
        float cfilled = i->getFilledSpace();
        if(cfilled < filled)
        {
            float add = (filled-cfilled)/2;

            if(add > _amount)
                add = _amount;
            _amount -= i->add(_item, add);
            filled = getFilledSpace();
        }
    }
}

float basicPipe::add(uint item, float amount) noexcept
{
    if(_item != 0xFFFFFFFF && _item != item && _amount > 0.05)
        return 0; // смешивать не будем

    if(_capacity - _amount < 0.05)
        return 0;

    _item = item;

    float newAmount = _amount+amount;
    if(newAmount >= _capacity)
    {
        _amount = _capacity;
        return amount-(newAmount - _capacity); // вернем что потратили
    }
    _amount += amount;

    return amount;
}

float basicPipe::require(uint item, float amount) noexcept
{
    if(_item != item || _item == 0xFFFFFFFF)
        return 0;

    if(_amount >= amount)
    {
        _amount -= amount;
        return amount;
    }

    amount = _amount;
    _amount = 0;
    return amount;
}

float basicPipe::getFilledSpace()
{
    return _amount/_capacity;
}

}
