#include <psemek/audio/track.hpp>
#include <psemek/util/exception.hpp>
#include <psemek/io/file_stream.hpp>

namespace psemek::audio
{

	namespace
	{

		struct lazy_track_impl
			: track
		{
			lazy_track_impl(std::filesystem::path const & path)
				: path_(path)
			{}

			stream_ptr stream() const override
			{
				load_proxy();
				return proxy_->stream();
			}

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

		private:
			std::filesystem::path path_;
			mutable track_ptr proxy_;

			void load_proxy() const
			{
				if (proxy_)
					return;

				auto data = io::read_full(io::file_istream(path_));
				auto const extension = path_.extension();
				if (extension == ".mp3")
					proxy_ = load_mp3(std::move(data));
				else if (extension == ".wav")
					proxy_ = load_wav(std::move(data));
				else if (extension == ".raw")
					proxy_ = load_raw(std::move(data));
				else
					throw util::exception("Unknown audio format: " + extension.string());
			}
		};

	}

	track_ptr load_lazy(std::filesystem::path const & path)
	{
		return std::make_shared<lazy_track_impl>(path);
	}

}
