#include <psemek/audio/effect/fade_in.hpp>
#include <psemek/audio/constants.hpp>

#include <algorithm>

namespace psemek::audio
{

	namespace
	{

		struct fade_in_impl
			: stream
		{
			fade_in_impl(stream_ptr stream, duration length, duration start)
				: stream_(std::move(stream))
				, length_(length)
				, start_(start)
			{}

			std::optional<std::size_t> length() const override
			{
				return stream_->length();
			}

			std::size_t played() const override
			{
				return stream_->played();
			}

			std::size_t read(util::span<float> samples) override
			{
				auto const count = stream_->read(samples);
				std::fill(samples.begin(), samples.begin() + std::min<std::size_t>(count, start_.samples()), 0.f);

				if (count <= start_.samples())
				{
					start_ -= count;
				}
				else
				{
					for (std::size_t i = start_.samples(); i < count; i += 2)
					{
						float m = static_cast<float>(std::min<std::size_t>(current_, length_.samples())) / length_.samples();

						samples[i + 0] *= m;
						samples[i + 1] *= m;

						current_ += 2;
					}
					start_ = duration{};
				}

				return count;
			}

		private:
			stream_ptr stream_;
			duration length_;
			duration start_;
			std::size_t current_ = 0;
		};

	}

	stream_ptr fade_in(stream_ptr stream, duration length, duration start)
	{
		return std::make_shared<fade_in_impl>(std::move(stream), length, start);
	}

}
