/** getTiles
  *
  * Given a map gets the tiles for the map
  */
int HandlerUtils::GetTiles(const Map& map, Magick::Image& tileset, std::vector<Magick::Image>& tiles)
{
    int numTilesX = tileset.columns() / map.GetTileWidth();
    int numTilesY = tileset.rows() / map.GetTileHeight();
    tiles.reserve(numTilesX * numTilesY);
    for (int i = 0; i < numTilesY; i++)
    {
        for (int j = 0; j < numTilesX; j++)
        {
            Magick::Geometry dim(map.GetTileWidth(), map.GetTileHeight(), j * map.GetTileWidth(), i * map.GetTileHeight());
            int index = i * numTilesX + j;
            tiles[index] = tileset;
            tiles[index].crop(dim);
        }
    }

    return 0;
}
/** layerToImage
  *
  * Converts a layer into an ImageMagick Image
  */
int HandlerUtils::LayerToImage(const Map& map, const Layer& layer, std::vector<Magick::Image>& tiles,
                               Magick::Image& image)
{
    for (unsigned int i = 0; i < map.GetHeight(); i++)
    {
        for (unsigned int j = 0; j < map.GetWidth(); j++)
        {
            int index = i * map.GetWidth() + j;
            int tile = layer[index];
            if (tile == -1)
                continue;
            image.composite(tiles[tile], j * map.GetTileWidth(), i * map.GetTileHeight(), Magick::AtopCompositeOp);
        }
    }

    return 0;
}
/** layerToImage
  *
  * Converts a layer into an ImageMagick Image
  */
int HandlerUtils::LayerToImage(const Map& map, const Layer& layer, Magick::Image& image)
{
    std::vector<Magick::Image> tiles;

    if (HandlerUtils::GetTiles(map, tiles))
        return -1;

    Magick::Color color = Magick::ColorRGB(0, 0, 0);
    color.alpha(0);
    int width = map.GetWidth() * map.GetTileWidth();
    int height = map.GetHeight() * map.GetTileHeight();
    image.matte(true);
    image.resize(Magick::Geometry(width, height));
    image.backgroundColor(color);
    image.erase();

    return HandlerUtils::LayerToImage(map, layer, tiles, image);
}