#include "common/world/BlockMap.h"

static constexpr BlockId EMPTY_BLOCK = 65535;

BlockMap::BlockMap(int length, BlockId id) : blocks(length, 1) {
    blocks.fill(0);
    map.reserve(2);
    map.add(id);
    map.add(EMPTY_BLOCK);
}

BlockId BlockMap::get(int index) const {
    return map[blocks.get(index)];
}

void BlockMap::set(int index, BlockId id) {
    for(int i = 0; i < map.getLength(); i++) {
        if(map[i] == id) {
            blocks.set(index, i);
            return;
        } else if(map[i] == EMPTY_BLOCK) {
            map[i] = id;
            blocks.set(index, i);
            return;
        }
    }
    blocks.resize(blocks.getBits() + 1);
    int mapId = map.getLength();
    map.resize(mapId * 2, EMPTY_BLOCK);
    map[mapId] = id;
    blocks.set(index, mapId);
}