#include <allegro.h>

#include <vector>

#include "anim.h"
#include "collide.h"

Anim::Anim()
{
    Clear();
}

Anim::~Anim()
{
    Clear();
}

void Anim::AddFrame(BITMAP *bmp)
{
    bitmaps.push_back(bmp);

    CMask *mask = create_mask(bmp); 
    masks.push_back(mask);
}

void Anim::Clear()
{
    bitmaps.clear();

    for(unsigned int i=0; i<masks.size(); ++i)
    {
	destroy_mask(masks[i]);
    }

    masks.clear();
    curframe = 0;
    x = y = 0;
    active = true;
}

void Anim::Draw(BITMAP *bmp)
{
    if(active)
    {
	if(bitmaps.size() != 0)
	{
	    assert( (curframe < (int) bitmaps.size()) && (curframe >= 0) ); 
	    draw_sprite(bmp, bitmaps[curframe], (int) x, (int) y);
	}
    }
}

void Anim::NextFrame()
{
    curframe++;
    if(curframe >= (int) bitmaps.size())    curframe = 0;

    assert( (curframe >= 0) && (curframe < (int) bitmaps.size()) );
}

void Anim::PrevFrame()
{
    curframe--;
    if(curframe < 0)    curframe = (int) bitmaps.size() - 1;

    assert( (curframe >= 0) && (curframe < (int) bitmaps.size()) );
}

const Anim &Anim::operator=(const Anim &src)
{
    if(&src != this)
    {
	Clear();
	bitmaps = src.bitmaps;

	for(unsigned int i=0; i<src.masks.size(); ++i)
	{
	    masks.push_back(copy_mask(src.masks[i]));
	}

	x = src.x;
	y = src.y;
	curframe = src.curframe;
	active = src.active;
    }

    return *this;
}

void Anim::SetX(float newx)   { x = newx; }
void Anim::SetY(float newy)   { y = newy; }
float Anim::X()   { return x; }
float Anim::Y()   { return y; }

int Anim::W() { return (bitmaps.size() > 0) ? bitmaps[0]->w : 0; }
int Anim::H() { return (bitmaps.size() > 0) ? bitmaps[0]->h : 0; }

bool Anim::Collide(CMask *mask, float bmpx, float bmpy)
{
    return check_collision(mask, (int) bmpx, (int) bmpy,
	masks[curframe], (int) x, (int) y);
}

void Anim::SetActive(bool newactive)    { active = newactive; }
bool Anim::Active() { return active; }
