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

#include "Enemy.h"
#include "MapLayer.h"
#include "DungeonGame.h"

Enemy::Enemy() :
Entity((rand() > .5*RAND_MAX)? "assets/characters/enemy1.png" : "assets/characters/enemy2.png")
{
	Entity("assets/characters/enemy2.png");
	setAnchorPoint(0.5, 0.7);
	animate("assets/anim/enemy/idle_down.spt");
	_turn = (rand() > 0.5*RAND_MAX);
	_colorMod = {0xff, 0xdd, 0x99, 0xff};
}

Enemy::~Enemy()
{
	
}

void Enemy::draw(SDL_Renderer *renderer)
{
	if(_parent == nullptr) return;
	
	MapLayer* map = (MapLayer*)_parent;
	float opacity = 1.0f - map->distanceToPlayer(_position.x, _position.y) /
					(float)(kVisionRadius*kTileSize);
	
	opacity = (opacity > 0)? opacity : 0.0f;
	opacity = (opacity < 1)? opacity : 1.0f;
	SDL_SetTextureColorMod(_texture,
						   _colorMod.red*map->flicker*opacity,
						   _colorMod.green*map->flicker*opacity,
						   _colorMod.blue*map->flicker*opacity);
	
	Entity::draw(renderer);
}

void Enemy::aiMove()
{
	_turn = !_turn;
	if(!_turn)
	{
		_moveController->decreaseEnemyMoves();
		return;
	}
	
	float distance = ((MapLayer*)_parent)->distanceToPlayer(_position.x, _position.y);
	EntityMotion motion;
	
	if (distance < kVisionRadius*kTileSize)
	{
		Point<float> ortho = ((MapLayer*)_parent)->orthoDistance(_position.x, _position.y);
		if(abs(ortho.x) > abs(ortho.y))
		{
			motion = (ortho.x < 0)? kMotionLeft : kMotionRight;
		}
		else
		{
			motion = (ortho.y < 0)? kMotionUp : kMotionDown;
		}
	}
	else
	{
		motion = (EntityMotion)(rand()%last);
	}
	move(motion);
	if(!_shouldMove)
	{
		_moveController->decreaseEnemyMoves();
	}
}

void Enemy::didStartMotion(EntityMotion direction)
{
	switch(direction)
	{
		case kMotionRight:
			animate("assets/anim/enemy/jump_right.spt");
			break;
		case kMotionLeft:
			animate("assets/anim/enemy/jump_left.spt");
			break;
		case kMotionUp:
			animate("assets/anim/enemy/jump_up.spt");
			break;
		case kMotionDown:
			animate("assets/anim/enemy/jump_down.spt");
			break;
		default:
			break;
	}
}

void Enemy::didFinishMotion(EntityMotion direction)
{
	switch(direction)
	{
		case kMotionRight:
			animate("assets/anim/enemy/idle_right.spt");
			break;
		case kMotionLeft:
			animate("assets/anim/enemy/idle_left.spt");
			break;
		case kMotionUp:
			animate("assets/anim/enemy/idle_up.spt");
			break;
		case kMotionDown:
			animate("assets/anim/enemy/idle_down.spt");
			break;
		default:
			break;
	}
	if(_moveController == nullptr) return;
	_moveController->decreaseEnemyMoves();
}