#include "Kebab.hpp"
#include "Echo.hpp"
#include "Player.hpp"

Texture Kebab::_tex;
Texture Kebab::_tex2;

Kebab::Kebab(Shared* context)
{
	_context = context;
	if(_tex.getSize().x == 0) {
		_tex.loadFromFile("data/kebab.png");
	}
	if(_tex2.getSize().x == 0) {
		_tex2.loadFromFile("data/kebab2.png");
	}
	keb.setTexture(_tex);
	spr.setTexture(_tex2);
	keb.setOrigin(16, 24);
	spr.setOrigin(16, 24);
	dead = 0;
	released = 1;
	phasing = 0;
}

Kebab::~Kebab()
{

}

void Kebab::loop(float delta)
{

	IntRect b = IntRect(getPosition().x + keb.getGlobalBounds().left,
					 getPosition().y + keb.getGlobalBounds().top + 24.f,
					 keb.getTextureRect().width,
					 keb.getTextureRect().height);

	for(unsigned i = 0; i < _context->gz.size(); ++i)
	{
		if(_context->gz[i].intersects(b))
		{
			   dead = true;
			   _context->gz[i].width = 0;
			   _context->_s += 100;
			   return;
		}
	}


	int phaseSpeed = 300;
	int a = keb.getColor().a;
	if(!released) {
		spr.move(delta * 160.f * spr.getScale().x, 0);
	}
	if(!phasing) {
		if(clk.getElapsedTime().asSeconds() > 16.f) {
			a -= delta * phaseSpeed;
			if(a <= 0)
				dead = true;
			else {
				keb.setColor(Color(255, 255, 255, a >= 0 ? a : 0));
			if(released) spr.setColor(Color(255, 255, 255, a >= 0 ? a : 0));
			}
		}
		else if(a < 255) {
			a += delta * phaseSpeed;
			keb.setColor(Color(255, 255, 255, a < 255 ? a : 255));
			if(released) spr.setColor(Color(255, 255, 255, a < 255 ? a : 255));
		}
		if(_context->p->getPosition().x + 48.f < getPosition().x) {
			if(spr.getScale().x == 1.f && rotcd.getElapsedTime().asSeconds() > 2.f) {
				spr.setScale(-1.f, 1.f);
				keb.setScale(-1.f, 1.f);
				rotcd.restart();
			}
		}
		else if(_context->p->getPosition().x - 48.f > getPosition().x) {
			if(spr.getScale().x == -1.f && rotcd.getElapsedTime().asSeconds() > 2.f) {
				spr.setScale(1.f, 1.f);
				keb.setScale(1.f, 1.f);
				rotcd.restart();
			}
		}
		else if(_context->p->getPosition().y != getPosition().y) {
			if(phasecd.getElapsedTime().asSeconds() > 4.f)
				phasing = true;
		}
		else {
			released = false;
		}
		move(delta * 120.f * keb.getScale().x, 0.f);
	}
	else {
		phasecd.restart();
		a -= delta * phaseSpeed;
		keb.setColor(Color(255, 255, 255, a >= 0 ? a : 0));
		if(released) spr.setColor(Color(255, 255, 255, a >= 0 ? a : 0));
		if(a <= 20) {
			phasing = false;
			move(0, 16.f);
		}
	}
}

void Kebab::draw(RenderTarget& target, RenderStates states) const
{
	states.transform *= getTransform();

	target.draw(spr, states);
	target.draw(keb, states);
}
