/*
 * Image.cpp
 *
 *  Created on: 5 dec 2011
 *      Author: Reii
 */
#include "Image.h"
#include "SDL/SDL.h"
#include <string>
#include <stdexcept>

using namespace std;

//Default constructor
Image::Image(){

}

//Copy constructor
Image::Image(const Image* other){
	surface = other->getSurface();
	surface->refcount++;
}

//Constructor with filename and transparent parameters
Image::Image(string filename, bool transparent){
	SDL_Surface* tmp = SDL_LoadBMP(filename.c_str());

	if(!tmp){
		throw invalid_argument("Unable to load image!");
	}else{
		surface = SDL_DisplayFormat(tmp);
		SDL_FreeSurface(tmp);
		if(transparent){
			Uint32 transp = *(Uint32*)surface->pixels;
			SDL_SetColorKey(surface, SDL_SRCCOLORKEY, transp);
		}
	}
}

const Image& Image::operator=(const Image& other){
	if(surface != other.getSurface()){
		if(surface != NULL && --surface->refcount == 0){
			delete surface;
		}
		surface = other.getSurface();
		if(surface){
			surface->refcount++;
		}
	}
	return *this;
}

//Returns the SDL_Surface connected to the image
SDL_Surface* Image::getSurface() const{
	return surface;
}

//Destructor
Image::~Image(){
	SDL_FreeSurface(surface);
}


