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

Fruit::Fruit(Collider* collider): 
m_collider(collider),
m_falling(true) {
	m_boom.setVolume(50.f);
	std::string str = "data/plop";
	str += char('1' + rand() % 3);
	str += ".ogg";
	m_boom.setBuffer(Asset::sound(str));
	setOrigin(0.f, 32.f);
	m_baseY = -1.f;
}

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

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