/**
 *  one room arena
 *  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 "Bullet.hpp"
#include "Map.hpp"
#include "Player.hpp"

Bullet::Bullet(Vector2f position, float angle, int strength): 
	_map(nullptr),
	_self(nullptr),
	_dead(false), 
	_strength(strength),
	_madeByPlayer(false)
{
	this->setPosition(position);
	this->setRotation(angle);
}

void Bullet::registerMap(Map* map)
{
	_map = map;
}
void Bullet::registerSelf(Player* player)
{
	_self = player;
}

RectBullet::RectBullet(Vector2f position, float angle, int strength): Bullet(position, angle, strength)
{
	this->setSize(Vector2f(2.f, 50.f));
	this->setOrigin(1.f, 25.f);
	_speed = 1200.f;
	_explosive = false;
}

NukeBullet::NukeBullet(Vector2f position, float angle, int strength): Bullet(position, angle, strength)
{
	_badlyAllocatedTexture.loadFromFile("data/fatman.png");
	this->setSize(Vector2f(64.f, 128.f));
	this->setOrigin(32.f, 64.f);
	this->setTexture(&_badlyAllocatedTexture);
	_speed = 200.f;
	_explosive = true;
}

void Bullet::update(float delta)
{
	this->move(Vector2f(std::sin(getRotation() * 3.1415f / 180.f), -std::cos(getRotation() * 3.1415f / 180.f)) * _speed * delta);
	
	for(unsigned i = 0; i < getPointCount(); ++i)
	{
		Vector2f pos = getTransform().transformPoint(getPoint(i));
		if(_map->collision(pos))
		{
			if(_explosive)
			{
				_map->destroy(getPosition(), _strength);
			}
			_dead = true;
			// delete this;
		}
		for(unsigned j = 0; j < Player::aiPlayer->size(); ++j)
		{
			if(Player::aiPlayer->at(j) == _self)
				continue;
			if(std::pow(Player::aiPlayer->at(j)->getPosition().x - pos.x, 2) + std::pow(Player::aiPlayer->at(j)->getPosition().y - pos.y, 2) < 50*50)
			{
				Player::aiPlayer->at(j)->kill(_madeByPlayer);
				_dead = true;
				break;
			}
		}
		if(Player::actualPlayer != _self)
		{
			if(std::pow(Player::actualPlayer->getPosition().x - pos.x, 2) + std::pow(Player::actualPlayer->getPosition().y - pos.y, 2) < 50*50)
			{
				Player::actualPlayer->kill(false);
				_dead = true;
			}
		}
	}
}

bool Bullet::isDead() const
{
	return _dead;
}

bool Bullet::isExplosive() const
{
	return _explosive;
}

void Bullet::setColor(Color color)
{
	this->setFillColor(color);
}

void Bullet::madeByPlayer()
{
	_madeByPlayer = true;
}
