#include "MultiblockTree.h"

#include "Block.h"

using namespace Framework;

MultiblockTree::MultiblockTree(
    int dimensionId, __int64 structureId, Framework::Vec3<int> uniquePosition)
    : MultiblockStructure(
        dimensionId, structureId, uniquePosition, MultiblockStructureEnum::TREE)
{}

void MultiblockTree::onBlockRemoved(Block* zBlock)
{
    if (isBlockMember(zBlock))
    {
        MultiblockStructure::onBlockRemoved(zBlock);
        for (int d = 4; d >= 0; d--)
        {
            bool foundStablizer = 0;
            Array<Block*> checked;
            Array<Block*> queue;
            Block* current = zBlock->zNeighbor(getDirectionFromIndex(d));
            if (current && isBlockMember(current)) queue.add(current);
            while (queue.getEintragAnzahl() > 0)
            {
                current = queue.get(0);
                queue.remove(0);
                Block* bottom = current->zNeighbor(BOTTOM);
                if (bottom && isBlockMember(bottom))
                {
                    foundStablizer = 1;
                    break;
                }
                checked.add(current);
                for (int i = 0; i < 4; i++)
                {
                    Block* neighbor
                        = current->zNeighbor(getDirectionFromIndex(i));
                    if (neighbor && isBlockMember(neighbor))
                    {
                        bool found = 0;
                        for (Block* b : checked)
                        {
                            if (b == neighbor)
                            {
                                found = 1;
                                break;
                            }
                        }
                        if (!found)
                        {
                            for (Block* b : queue)
                            {
                                if (b == neighbor)
                                {
                                    found = 1;
                                    break;
                                }
                            }
                        }
                        if (!found) queue.add(neighbor);
                    }
                }
            }
            if (!foundStablizer)
            {
                for (Block* b : checked)
                    b->setHP(0);
            }
        }
    }
}

MultiblockTreeStructureType::MultiblockTreeStructureType()
    : MultiblockStructureType(MultiblockStructureEnum::TREE)
{}

MultiblockStructure* MultiblockTreeStructureType::createStructure(
    int dimensionId,
    __int64 structureId,
    Framework::Vec3<int> uniquePosition) const
{
    return new MultiblockTree(dimensionId, structureId, uniquePosition);
}