/*
 * Player.cpp
 *
 *  Created on: 16 dec 2011
 *      Author: Reii
 */

#include "SDL/SDL.h"
#include "Player2.h"
#include "Globals.h"
#include <string>
#include "Enemy.h"
#include "Life.h"

using namespace std;

Player2::Player2(string filename, bool transparent, bool multi, int x, int y):
Sprite(filename, transparent, multi, x, y){
	lives = 2;
}

Player2::Player2(Image* img, bool multi, int x, int y):
Sprite(img, multi, x, y){
	lives = 2;
}

Player2* Player2::getInstance(string filename, bool transparent, bool multi, int x, int y){
	return new Player2(filename, transparent, multi, x, y);
}

Player2* Player2::getInstance(Image* img, bool multi, int x, int y){
	return new Player2(img, multi, x, y);
}

void Player2::tick(vector<Sprite*>& gameobjects){
	moveSprite(getXspeed(), getYspeed());
	detectBorderCollision();

	vector<Sprite*>::iterator iter;
	for(iter = gameobjects.begin() ; iter != gameobjects.end();){
		if(*iter != this && hasCollided(*iter)){

			if(Life* l = dynamic_cast<Life*>(*iter)){
				delete *iter;
				iter = gameobjects.erase(iter);
				lives++;

			}else if(Enemy* e = dynamic_cast<Enemy*>(*iter)){
				delete *iter;
				iter = gameobjects.erase(iter);
				if(lives-- == 0){
					globals.Quit();
					globals.setMenu("Images/P1Menu.bmp");
				}
			}else{
				moveSprite(-getXspeed(), -getYspeed());
				++iter;
			}
		}else{
			++iter;
		}
	}
}

void Player2::keyDown(SDLKey key){
	switch(key){
	case SDLK_w:
		setYspeed(-20);
		break;
	case SDLK_s:
		setYspeed(20);
		break;
	case SDLK_a:
		setXspeed(-20);
		break;
	case SDLK_d:
		setXspeed(20);
		break;
	default:
		break;
	}
}

void Player2::keyUp(SDLKey key){
	switch(key){
	case SDLK_w:
		setYspeed(0);
		break;
	case SDLK_s:
		setYspeed(0);
		break;
	case SDLK_a:
		setXspeed(0);
		break;
	case SDLK_d:
		setXspeed(0);
		break;
	default:
		break;
	}
}

void Player2::draw(){
	SDL_Rect rect = getRect();
	SDL_Rect clip[ 4 ];

	//Clip range for the top left 
	clip[ 0 ].x = 0; 
	clip[ 0 ].y = 0; 
	clip[ 0 ].w = 80; 
	clip[ 0 ].h = 80; 
	//Clip range for the top right 
	clip[ 1 ].x = 80; 
	clip[ 1 ].y = 0; 
	clip[ 1 ].w = 80; 
	clip[ 1 ].h = 80; 
	//Clip range for the bottom left 
	clip[ 2 ].x = 0; 
	clip[ 2 ].y = 80; 
	clip[ 2 ].w = 80; 
	clip[ 2 ].h = 80; 
	
	if(lives >= 2){
		SDL_BlitSurface(getImage()->getSurface(), &clip[0], globals.getScreen(), &rect);
	}else if(lives == 1){
		SDL_BlitSurface(getImage()->getSurface(), &clip[1], globals.getScreen(), &rect);
	}else if(lives == 0){
		SDL_BlitSurface(getImage()->getSurface(), &clip[2], globals.getScreen(), &rect);
	}
}

Player2::~Player2(){

}

