#ifndef _TMAIMAGEBANK_CPP_
#define _TMAIMAGEBANK_CPP_

#include "ma_allegro.h"

REGISTER_CLASS_ID(TMAImageBank);

TMAImageBank *TMAImageBank::createStatic(const char *filename,int tx,int ty,int ax,int ay,bool separator)
{
    TMABitmap *bmp = TMABitmap::loadFromFile(filename);
    if (bmp==NULL) return NULL;
    
    TMAImageBank *ibank = createStatic(*bmp,tx,ty,ax,ay,separator);
    delete bmp;
    
    return ibank;
}

TMAImageBank *TMAImageBank::createStatic(TMABitmap& bmp,int tx,int ty,int ax,int ay,bool separator)
{
    int size = tx*ty,index=0;
    int depth = bmp.getColorDepth();
    TMAImageBank *ibank = new TMAImageBank();
    
    if (ibank==NULL) return NULL;
    ibank->vector.redim(size);
    ibank->vector.fillEmpty(size);
    
    for (int y=0;y<ty;y++)
    {
        for (int x=0;x<tx;x++)
        {
            PMABitmap img = TMABitmap::create(ax,ay,depth);
            if (img==NULL)
            {
                delete ibank;
                return NULL;
            }
            if (!separator) img->draw(&bmp,x*ax,y*ay,ax,ay,0,0,false);
            else img->draw(&bmp,x*(ax+1),y*(ay+1),ax,ay,0,0,false);
            ibank->vector.replaceElementAt(img,index++);
        }
    }
    return ibank;
}
            
TMAImageBank *TMAImageBank::createDynamic(const char *filename,TMAVector& zonas)
{
    TMABitmap *bmp = TMABitmap::loadFromFile(filename);
    if (bmp==NULL) return NULL;
    
    TMAImageBank *ibank = createDynamic((*bmp),zonas);
    delete bmp;
    
    return ibank;
}    

TMAImageBank *TMAImageBank::createDynamic(TMABitmap& bmp,TMAVector& zonas)
{
    TMAImageBank *ibank = new TMAImageBank();
    if (ibank==NULL) return NULL;
    int depth = bmp.getColorDepth();
    ibank->vector.redim(zonas.size());
    ibank->vector.fillEmpty(zonas.size());
    
    for (int index=0;index<zonas.size();index++)
    {
        PMAObject obj = zonas.elementAt(index);
        if (obj!=NULL && obj->isInstanceOf(CLASS_ID(TMARectangle)))
        {
            PMARectangle rect = (PMARectangle)obj;   
            PMABitmap img = TMABitmap::create(rect->width,rect->height,depth);
            if (img==NULL)
            {
                delete ibank;
                return NULL;
            }
            img->draw(&bmp,rect->x,rect->y,rect->width,rect->height,0,0,false);
            ibank->vector.replaceElementAt(img,index);
        }
    }
    
    return ibank;    
}
    
// Devuelve una imagen del banco de imágenes, que esta indexada
// por el indice especificado.
//
const PMABitmap TMAImageBank::getBitmap(int index)
{
    return (PMABitmap)vector.elementAt(index);
}

long TMAImageBank::size(void) 
{ 
    return vector.size(); 
}

#endif
