#include <cmath>
#include "Log.hpp"
#include "Spike.hpp"
#include "Collider.hpp"
#include "Asset.hpp"

Spike::Spike(Collider* collider, bool alive): 
m_collider(collider),
m_falling(false),
m_alive(alive) {
	m_boom.setVolume(60.f);
	m_boom.setBuffer(Asset::sound("data/boom.ogg"));
}

void Spike::registerColl() {
	m_collider->setBlock((getPosition().x + 16.f - m_collider->getLocalX()) / 32.f, (getPosition().y) / 32.f, Collider::SPIKE);
	m_collider->setBlock((getPosition().x + 16.f - m_collider->getLocalX()) / 32.f, (getPosition().y + 31.f) / 32.f, Collider::SPIKE);
}

void Spike::update(float delta) {
	if(!m_alive) {
		registerColl();
		return;
	}
    bool should_fall = false;
	
    sf::Vector2i bottom;
    bottom.x = (getPosition().x + 16.f - m_collider->getLocalX()) / 32.f;
    bottom.y = (getPosition().y + 32.f) / 32.f;
    should_fall = !m_collider->isSolid(bottom.x, bottom.y);
	
	registerColl();
	
    if(!m_hold) {
		if(should_fall) {
			if(!m_falling) {
				m_clock.restart();
				m_falling = true;
				m_baseY = getPosition().y;
			}
			setPosition(getPosition().x, m_baseY + 200 * std::pow(m_clock.getElapsedTime().asSeconds(), 2));
		} else if(m_falling) {
			m_falling = false;
			setPosition(getPosition().x, (bottom.y - 1) * 32.f);
			m_boom.setPitch(0.8 + (rand() % 21) / 50.f); //0.8-1.2
			m_boom.play();
		}
	}
}

void Spike::move(float dy) {
	sf::Sprite::move(0.f, dy);
	m_hold = true;
}

void Spike::release() {
	m_hold = false;
}
