//
//  Entity.cpp
//  GlobalGameJam15
//
//  Created by Cesar Parent on 24/01/2015.
//  Copyright (c) 2015 Cesar Parent. All rights reserved.
//

#include "Entity.h"
#include "MapLayer.h"
#include "Defines.h"
#include "DungeonGame.h"


const Point<int> Entity::moves[4] = {
	{0,-1},
	{0,1},
	{-1,0},
	{1,0},
};

Entity::Entity(std::string sprite) :
	SpriteEmitter(sprite)
{
	_shouldMove = false;
}

Entity::~Entity()
{
	
}

void Entity::move(EntityMotion direction)
{
	if(_parent == nullptr) return;
	if((_targetTile.x+.5)*kTileSize != _position.x ||
	   (_targetTile.y+.5)*kTileSize != _position.y) return;
	MapLayer* map = (MapLayer*)_parent;
	
	Point<int> move = moves[direction];
	Point<int> target = Point<int>(_tileLocation.x + move.x, _tileLocation.y + move.y);
	
	if(!map->moveAllowed(target))
	{
		_shouldMove = false;
		return;
	}
	didStartMotion(direction);
	_shouldMove = true;
	_targetMove = move;
	_targetTile = target;
}

void Entity::setTile(int x, int y)
{
	_tileLocation = Point<int>(x, y);
	_targetTile = Point<int>(x, y);
	_targetMove = Point<int>(0, 0);
	setX((_tileLocation.x + 0.5) * kTileSize);
	setY((_tileLocation.y + 0.5) * kTileSize);
}

Point<int> Entity::tile()
{
	return Point<int>((int)_position.x/kTileSize, (int)_position.y/kTileSize);
}

Point<int> Entity::targetTile()
{
	return _targetTile;
}

Point<float> Entity::_targetPoint()
{
	return Point<float>((_targetTile.x+0.5)*kTileSize, (_targetTile.y+0.5)*kTileSize);
}

void Entity::update(int timeInterval)
{
	SpriteEmitter::update(timeInterval);
	
	if(!_shouldMove) return;
	
	Point<float> aim = _targetPoint();
	
	if(_targetMove.x == 0 && _targetMove.y != 0)
	{
		//vertical motion
		setY(_position.y + _targetMove.y*2);
		if(_position.y == aim.y)
		{
			didFinishMotion((_targetMove.y < 0)? kMotionUp : kMotionDown);
			setTile(_targetTile.x, _targetTile.y);
			_shouldMove = false;
		}
	}
	else if(_targetMove.y == 0 && _targetMove.x != 0)
	{
		//horizontal motion
		setX(_position.x + _targetMove.x*2);
		if(_position.x == aim.x)
		{
			didFinishMotion((_targetMove.x < 0)? kMotionLeft : kMotionRight);
			setTile(_targetTile.x, _targetTile.y);
			_shouldMove = false;
		}
	}
}