/**
 *  Triangles
 *  Copyright (C) 2016 POSITIVE MENTAL ATTITUDE
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cmath>
#include "Utility.hpp"
#include "Wormhole.hpp"

Wormhole::Wormhole(): Lantern()
{
	light()->_emissionSprite.setColor(sf::Color::White);
	light()->_localCastCenter = sf::Vector2f(0.0f, 0.0f);
	_sprite.setPosition(0, 0);
}

void Wormhole::load(const sf::Texture& texture1, const sf::Texture& texture2)
{
	_sprite.setTexture(texture1);
	_sprite.setOrigin(sf::Vector2f(texture1.getSize() / 2u));
	
	light()->_emissionSprite.setTexture(texture2);
	light()->_emissionSprite.setOrigin(sf::Vector2f(texture2.getSize() / 2u));
}

Wormhole::~Wormhole()
{
	Echo::debug("Deleting a wormhole.");
}

sf::Vector2f Wormhole::getPosition()
{
	return _sprite.getPosition();
}

void Wormhole::update(sf::Time delta)
{
	float degree = delta.asSeconds() * 36.f;
	_sprite.rotate(degree);
	light()->_emissionSprite.rotate(degree);
}

void Wormhole::setPosition(sf::Vector2f position)
{
	_sprite.setPosition(position);
	light()->_emissionSprite.setPosition(position);
}

void Wormhole::setPosition(float x, float y)
{
	setPosition(sf::Vector2f(x, y));
}

float Wormhole::gravity(sf::Vector2f position)
{
	sf::Vector2f delta = position - _sprite.getPosition();
	if(delta.x > -1.f && delta.y > -1.f && delta.x < 1.f && delta.y < 1.f)
		return 1.f;
	return std::sqrt(delta.x * delta.x + delta.y * delta.y);
}

sf::Vector2f Wormhole::direction(sf::Vector2f position)
{
	sf::Vector2f f;
	sf::Vector2f delta = _sprite.getPosition() - position;
	float length = sqrt(delta.x * delta.x + delta.y * delta.y);

	if(length > 0)
	{
		f.x = delta.x / length;
		f.y = delta.y / length;
	}

	return f;
}

void Wormhole::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	target.draw(_sprite);
}

