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

using namespace std;

Sprite::Sprite(string filename, bool transparent, bool multi, int x, int y){
	img = new Image(filename, transparent);
	collisionBox.x = x;
	collisionBox.y = y;
	if(multi){
		collisionBox.w = img->getSurface()->w/2;
		collisionBox.h = img->getSurface()->h/2;
	}else{	
		collisionBox.w = img->getSurface()->w;
		collisionBox.h = img->getSurface()->h;
	}
	xSpeed = 0, ySpeed = 0;
}

Sprite::Sprite(Image* img, bool multi, int x, int y){
	this->img = new Image(img);
	collisionBox.x = x;
	collisionBox.y = y;
	if(multi){
		collisionBox.w = img->getSurface()->w/2;
		collisionBox.h = img->getSurface()->h/2;
	}else{	
		collisionBox.w = img->getSurface()->w;
		collisionBox.h = img->getSurface()->h;
	}
	xSpeed = 0, ySpeed = 0;
}

void Sprite::mouseDown(int x, int y){}
void Sprite::mouseUp(int x, int y){}
void Sprite::mouseMoved(int x, int y){}
void Sprite::keyDown(SDLKey key){}
void Sprite::keyUp(SDLKey key){}

void Sprite::detectBorderCollision(){
	if(getRect().x < globals.getScreen()->clip_rect.x){
		moveSprite(-getXspeed(),0);
	}
	if(getRect().x+getRect().w > globals.getScreen()->clip_rect.x+globals.getScreen()->clip_rect.w+(getXspeed()/2)){
		moveSprite(-getXspeed(),0);
	}
	if(getRect().y < globals.getScreen()->clip_rect.y){
		moveSprite(0,-getYspeed());
	}
	if(getRect().y+getRect().h > globals.getScreen()->clip_rect.y+globals.getScreen()->clip_rect.h+(getYspeed()/2)){
		moveSprite(0, -getYspeed());
	}
}

void Sprite::moveSprite(int x, int y){
	collisionBox.x += x;
	collisionBox.y += y;
}

void Sprite::setXspeed(int speed){
	xSpeed = speed;
}

void Sprite::setYspeed(int speed){
	ySpeed = speed;
}

int Sprite::getXspeed(){
	return xSpeed;
}

int Sprite::getYspeed(){
	return ySpeed;
}

int Sprite::getX(){
	return getRect().x;
}

int Sprite::getY(){
	return getRect().y;
}

bool Sprite::hasCollided(const Sprite* other){
	int left = collisionBox.x;
	int right = collisionBox.x + collisionBox.w;
	int top = collisionBox.y;
	int bottom = collisionBox.y + collisionBox.h;

	int otherleft = other->collisionBox.x;
	int otherright = other->collisionBox.x + collisionBox.w;
	int othertop = other->collisionBox.y;
	int otherbottom = other->collisionBox.y + collisionBox.h;

	if(left >= otherright) return false;
	if(right <= otherleft) return false;
	if(top >= otherbottom) return false;
	if(bottom <= othertop) return false;

	return true;
}

Image* Sprite::getImage() const{
	return img;
}

SDL_Rect Sprite::getRect() const{
	return collisionBox;
}

Sprite::~Sprite(){
	delete img;
}


