//
//  CompoundSource.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/12/2017.
//  Copyright 2017 Thomas Harte. All rights reserved.
//

#ifndef CompoundSource_h
#define CompoundSource_h

#include "SampleSource.hpp"

#include <cassert>
#include <cstring>

namespace Outputs {
namespace Speaker {

/*!
	A CompoundSource adds together the sound generated by multiple individual SampleSources.
	An owner may optionally assign relative volumes.
*/
template <typename... T> class CompoundSource:
	public Outputs::Speaker::SampleSource {
	public:
		CompoundSource(T &... sources) : source_holder_(sources...) {
			// Default: give all sources equal volume.
			const float volume = 1.0f / static_cast<float>(source_holder_.size());
			for(std::size_t c = 0; c < source_holder_.size(); ++c) {
				volumes_.push_back(volume);
			}
		}

		void get_samples(std::size_t number_of_samples, std::int16_t *target) {
			source_holder_.template get_samples<get_is_stereo()>(number_of_samples, target);
		}

		void skip_samples(const std::size_t number_of_samples) {
			source_holder_.skip_samples(number_of_samples);
		}

		void set_sample_volume_range(int16_t range) {
			volume_range_ = range;
			push_volumes();
			source_holder_.set_scaled_volume_range(range, volumes_.data());
		}

		/*!
			Sets the relative volumes of the various sources underlying this
			compound. The caller should ensure that the number of items supplied
			matches the number of sources and that the values in it sum to 1.0.
		*/
		void set_relative_volumes(const std::vector<float> &volumes) {
			assert(volumes.size() == source_holder_.size());
			volumes_ = volumes;
			push_volumes();
		}

		static constexpr bool get_is_stereo() { return CompoundSourceHolder<T...>::get_is_stereo(); }

	private:
		void push_volumes() {
			source_holder_.set_scaled_volume_range(volume_range_, volumes_.data());
		}

		template <typename... S> class CompoundSourceHolder: public Outputs::Speaker::SampleSource {
			public:
				template <bool output_stereo> void get_samples(std::size_t number_of_samples, std::int16_t *target) {
					std::memset(target, 0, sizeof(std::int16_t) * number_of_samples);
				}

				void set_scaled_volume_range(int16_t range, float *volumes) {}

				std::size_t size() {
					return 0;
				}

				static constexpr bool get_is_stereo() {
					return false;
				}
		};

		template <typename S, typename... R> class CompoundSourceHolder<S, R...> {
			public:
				CompoundSourceHolder(S &source, R &...next) : source_(source), next_source_(next...) {}

				template <bool output_stereo> void get_samples(std::size_t number_of_samples, std::int16_t *target) {
					// Get the rest of the output.
					next_source_.template get_samples<output_stereo>(number_of_samples, target);

					if(source_.is_zero_level()) {
						// This component is currently outputting silence; therefore don't add anything to the output
						// audio — just pass the call onward.
						source_.skip_samples(number_of_samples);
						return;
					}

					// Get this component's output.
					auto buffer_size = number_of_samples * (output_stereo ? 2 : 1);
					int16_t local_samples[buffer_size];
					source_.get_samples(number_of_samples, local_samples);

					// Merge it in; furthermore if total output is stereo but this source isn't,
					// map it to stereo.
					if constexpr (output_stereo == S::get_is_stereo()) {
						while(buffer_size--) {
							target[buffer_size] += local_samples[buffer_size];
						}
					} else {
						// This will happen only if mapping from mono to stereo, never in the
						// other direction, because the compound source outputs stereo if any
						// subcomponent does. So it outputs mono only if no stereo devices are
						// in the mixing chain.
						while(buffer_size--) {
							target[buffer_size] += local_samples[buffer_size >> 1];
						}
					}

					// TODO: accelerate above?
				}

				void skip_samples(const std::size_t number_of_samples) {
					source_.skip_samples(number_of_samples);
					next_source_.skip_samples(number_of_samples);
				}

				void set_scaled_volume_range(int16_t range, float *volumes) {
					source_.set_sample_volume_range(static_cast<int16_t>(static_cast<float>(range * volumes[0])));
					next_source_.set_scaled_volume_range(range, &volumes[1]);
				}

				std::size_t size() {
					return 1+next_source_.size();
				}

				static constexpr bool get_is_stereo() {
					return S::get_is_stereo() || CompoundSourceHolder<R...>::get_is_stereo();
				}

			private:
				S &source_;
				CompoundSourceHolder<R...> next_source_;
		};

		CompoundSourceHolder<T...> source_holder_;
		std::vector<float> volumes_;
		int16_t volume_range_ = 0;
};

}
}

#endif /* CompoundSource_h */
