#include <ChunkHandle/ChunkHandle.hpp>
#include <World/World.hpp>

ChunkHandle::ChunkHandle(World &world, std::shared_ptr<Chunk> chunk) : world(world), chunk(chunk) {};

ChunkHandle::ChunkHandle(const ChunkHandle &other) : world(other.world), chunk(other.chunk)
{
    chunk->retainCount++;
}

ChunkHandle::~ChunkHandle()
{
    if (--chunk->retainCount == 0)
    {
        world.enqueueForPurge(chunk);
    }
}

Chunk& ChunkHandle::operator*()
{
    return *chunk;
}

Chunk* ChunkHandle::operator->() const
{
    return chunk.get();
}

ChunkHandle::operator std::shared_ptr<Chunk>()
{
    return chunk;
}

ChunkHandle& ChunkHandle::operator=(const ChunkHandle &other)
{
    if (--chunk->retainCount == 0)
    {
        world.enqueueForPurge(chunk);
    }

    chunk = other.chunk;
    chunk->retainCount++;

    return *this;
}

bool ChunkHandle::operator==(const ChunkHandle &other) const
{
    return chunk == other.chunk;
}