/*
 * Sheet.cpp
 *
 *  Created on: 2009-07-10
 *      Author: wasyl
 */

#include "Sheet.h"

#include <cstdio>
#include <allegro5/allegro.h>
#include <allegro5/a5_iio.h>
#include <allegro5/a5_color.h>

#include "../Common.h"

Sheet::Sheet(const char *filename)
{
	ALLEGRO_BITMAP *base = al_load_bitmap(filename);
	if (!base)
	{
		std::printf("UNABLE TO LOAD BITMAP '%s'!", filename);
		std::exit(1);
	}
	al_lock_bitmap(base, al_get_bitmap_format(base), ALLEGRO_LOCK_READONLY);

	int width = 0, height = 0;
	unsigned char r, g, b;

	while (true)
	{
		al_unmap_rgb(al_get_pixel(base, width, 0), &r, &g, &b);
		if ((r == 255) && (g == 0) && (b == 255))
			break;
		width++;
	}

	while (true)
	{
		al_unmap_rgb(al_get_pixel(base, 0, height), &r, &g, &b);
		if ((r == 255) && (g == 0) && (b == 255))
			break;
		height++;
	}

	al_unlock_bitmap(base);

	// ----

	mBase = base;
	mTileWidth = width;
	mTileHeight = height;

	int tiles_w = (al_get_bitmap_width(base) + 1)  / (width + 1);
	int tiles_h = (al_get_bitmap_height(base) + 1) / (height + 1);

	for (int x = 0; x < tiles_w; x++)
		for (int y = 0; y < tiles_h; y++)
			mTiles.push_back(al_create_sub_bitmap(base, x * (width+1), y * (height+1), width, height));
}

Sheet::~Sheet()
{
	FOREACH(vector,ALLEGRO_BITMAP*,b,mTiles)
	{
		al_destroy_bitmap(*b);
	}
	al_destroy_bitmap(mBase);
}
