#include "TinyLibrary.hpp"
#include "Resource.hpp"
#include "Game.hpp"
#include "Hiyoko.hpp"

Hiyoko::Hiyoko(void)
:type(TYPE_1)
{
}

Hiyoko::~Hiyoko(void)
{
}

void Hiyoko::Update(void)
{
	if(GetStatus() == Enemy::STATUS_DEAD)
	{
		return;
	}
	if(this->alive == true)
	{
		if(this->direction == 0)
		{
			this->vx = -500;
		}
		else
		{
			this->vx = 500;
		}
		++ this->anime_count;
		if(this->anime_count > 12)
		{
			this->anime_count = 0;
		}
		int push_back;
		if(this->vx > 0)
		{
			// Wall collision
			push_back = this->bg_map->GetPushBackLeft(this->x / 1000 + 10, this->y / 1000 + 8);
			if(push_back != 0)
			{
				this->vx = 0;
				this->x -= (push_back * 1000);
				this->direction = 1 - this->direction;
			}
			if(this->type == TYPE_2)
			{
				// Foot collision
				unsigned char foot_chip = this->bg_map->GetScreenChip(this->x / 1000 + 10 - 4, this->y / 1000 + 10);
				if(foot_chip == 0)
				{
					this->vx = 0;
					this->x -= (push_back * 1000);
					this->direction = 1 - this->direction;
				}
			}
		}
		else if(this->vx < 0)
		{
			// Wall collision
			push_back = this->bg_map->GetPushBackRight(this->x / 1000, this->y / 1000 + 8);
			if(push_back != 0)
			{
				this->vx = 0;
				this->x -= (push_back * 1000);
				this->direction = 1 - this->direction;
			}
			if(this->type == TYPE_2)
			{
				// Foot collision
				unsigned char foot_chip = this->bg_map->GetScreenChip(this->x / 1000 + 4, this->y / 1000 + 10);
				if(foot_chip == 0)
				{
					this->vx = 0;
					this->x -= (push_back * 1000);
					this->direction = 1 - this->direction;
				}
			}
		}
	}
	Enemy::Update();
}

void Hiyoko::Draw(void)
{
	Screen& screen = Screen::GetInstance();
	int x = this->x / 1000;
	int y = this->y / 1000;
	if(this->direction == 0)
	{
		if(this->anime_count < 6)
		{
			ImageData* image_data = GetImageData(HIYOKO_L_1);
			screen.DrawSprite(image_data->buffer, x, y, image_data->width, image_data->height, 0);
		}
		else
		{
			ImageData* image_data = GetImageData(HIYOKO_L_2);
			screen.DrawSprite(image_data->buffer, x, y, image_data->width, image_data->height, 0);
		}
	}
	else
	{
		if(this->anime_count < 6)
		{
			ImageData* image_data = GetImageData(HIYOKO_R_1);
			screen.DrawSprite(image_data->buffer, x, y, image_data->width, image_data->height, 0);
		}
		else
		{
			ImageData* image_data = GetImageData(HIYOKO_R_2);
			screen.DrawSprite(image_data->buffer, x, y, image_data->width, image_data->height, 0);
		}
	}
}

void Hiyoko::SetType(int type)
{
	this->type = type;
}
