/*
 * ResourceBase.h
 *
 *  Created on: 2009-07-08
 *      Author: wasyl
 */

#ifndef RESOURCEBASE_H_
#define RESOURCEBASE_H_

#include <allegro5/allegro.h>
#include <allegro5/a5_iio.h>
#include <allegro5/a5_font.h>
#include <allegro5/a5_ttf.h>
#include <allegro5/acodec.h>
#include <allegro5/kcm_audio.h>

#include <cstdlib>
#include <string>

/**********************************************/

class ResourceBase
{
protected:
	std::string mFilename;

public:
	ResourceBase(const char *filename) : mFilename(filename) {}
	virtual ~ResourceBase() {};

	const char *filename() { return mFilename.c_str(); }
};

/**********************************************/

template <class T>
class Resource : public ResourceBase
{
private:
	T *content;

public:
	Resource(const char *filename) : ResourceBase(filename)
	{
		content = new T(filename);
	}

	~Resource()
	{
		delete content;
	}

	T *grab() { return content; }
};

/**********************************************/

template <>
class Resource<ALLEGRO_BITMAP> : public ResourceBase
{
private:
	ALLEGRO_BITMAP *content;

public:
	Resource(const char *filename) : ResourceBase(filename)
	{
		content = al_load_bitmap(filename);
		if (!content)
		{
			std::printf("Unable to find resource: '%s'.\n", filename);
			std::exit(1);
		}
	}

	~Resource()
	{
		al_destroy_bitmap(content);
	}

	ALLEGRO_BITMAP *grab() { return content; }
};

template <>
class Resource<ALLEGRO_FONT> : public ResourceBase
{
private:
	ALLEGRO_FONT *content;

public:
	Resource(const char *filename) : ResourceBase(filename)
	{
		content = al_load_font(filename, 13, 0);
		if (!content)
		{
			std::printf("Unable to find resource: '%s'.\n", filename);
			std::exit(1);
		}
	}

	~Resource()
	{
		al_destroy_font(content);
	}

	ALLEGRO_FONT *grab() { return content; }
};

template <>
class Resource<ALLEGRO_SAMPLE> : public ResourceBase
{
private:
	ALLEGRO_SAMPLE *content;

public:
	Resource(const char *filename) : ResourceBase(filename)
	{
		content = al_load_sample_wav(filename);
		if (!content)
			content = al_load_sample(filename);
		if (!content)
		{
			unsigned char *buffer = new unsigned char[1];
			buffer[0] = 128;
			content = al_create_sample(buffer, 1, 44100, ALLEGRO_AUDIO_DEPTH_UINT8, ALLEGRO_CHANNEL_CONF_1, true);
			std::printf("Unable to load sound (no SNDFILE support?): '%s'.\nFalling back to no sound.\n", filename);
		}
	}

	~Resource()
	{
		al_destroy_sample(content);
	}

	ALLEGRO_SAMPLE *grab() { return content; }
};

/**********************************************/

#endif /* RESOURCEBASE_H_ */
