//---------------------------
// Includes
//---------------------------
#include "StdAfx.h"
#include "resource.h"
#include "Enemy.h"

#include "Painter.h"
#include "ResourceLoader.h"
#include "InputState.h"
#include "CollisionMesh.h"
#include "Image.h"
#include "TextFormat.h"
#include "Audio.h"

//---------------------------
// Defines
//---------------------------
//

//---------------------------
// Constructor & Destructor
//---------------------------
Enemy::Enemy(ResourceLoader* resourceLoaderPtr,const String& imagename,int hitPoints)
:Character(resourceLoaderPtr,imagename,hitPoints)
,m_Range(200)
,m_AlreadyHit(false)
,m_Attack(false)
,m_AttackTimer(-1)
{
	m_Speed = 77;
	m_HeadingRight = false;
}

Enemy::~Enemy()
{

}

void Enemy::Tick(InputState *inputStatePtr, Hero *hero)
{
	DetermineReactionToHero(hero);
}

void Enemy::DetermineReactionToHero(Hero *hero)
{
	CollisionMesh *characterWeaponMesh = hero->GetWeaponCollisionMesh();
	detectHealthChange(characterWeaponMesh,hero->GetDamageAmount());
}

void Enemy::detectHealthChange(CollisionMesh *collisionMesh, int healthModifier)
{
	if(!m_dead)
	{
		//Determines whether a collisionmesh comes into contact with the Enemy
		if(m_HCollisionMeshPtr->HitTest(collisionMesh) || m_VCollisionMeshPtr->HitTest(collisionMesh))
		{
			if(!m_AlreadyHit)
			{
				Rect2D weaponBounds = collisionMesh->GetBounds();
				Rect2D hMeshBounds = m_HCollisionMeshPtr->GetBounds();
				bool rightHit = true;

				double difMin= fabs(weaponBounds.MinX - hMeshBounds.MinX);
				double difMax = fabs(weaponBounds.MaxX - hMeshBounds.MaxX);

				//checks whether the weapon is hitting on the left. If not, it is hitting on theright
				if( difMin < difMax)
				{
					rightHit = false;
				}

				//When the direction the hero is facing, is the same as the side on which he is hit, he will block it,
				// unless the attack was too hard.
				if((m_HeadingRight && rightHit)||(!m_HeadingRight && !rightHit))
				{
					if(healthModifier < -1)
					{
						ChangeCurrentHitPoints(healthModifier);
						SetCurrentState(STATE_HIT);
						m_AlreadyHit = true;
					} else {
						SetCurrentState(STATE_BLOCKING);
					}
				} else {
					//When the Enemy gets hit in his back, he receives damage
					ChangeCurrentHitPoints(healthModifier);
					SetCurrentState(STATE_HIT);
					m_HeadingRight = !m_HeadingRight;
				}
			}
		} else {
			m_AlreadyHit = false;
		}
	}
}
