#include <psemek/audio/effect/truncate.hpp>

#include <algorithm>

namespace psemek::audio
{

	namespace
	{

		struct truncate_impl
			: stream
		{
			truncate_impl(stream_ptr stream, duration length)
				: stream_(std::move(stream))
				, length_(length)
			{}

			std::optional<std::size_t> length() const override
			{
				return length_.samples();
			}

			std::size_t read(util::span<float> samples) override
			{
				auto played = stream_->played();
				auto max_count = std::min<std::size_t>(length_.samples() - played, samples.size());
				return stream_->read(samples.prefix(max_count));
			}

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

		private:
			stream_ptr stream_;
			duration length_;
		};

	}

	stream_ptr truncate(stream_ptr stream, duration length)
	{
		return std::make_shared<truncate_impl>(std::move(stream), length);
	}

}
