#include <psemek/audio/engine.hpp>
#include <psemek/audio/constants.hpp>
#include <psemek/log/log.hpp>
#include <psemek/prof/profiler.hpp>
#include <psemek/util/at_scope_exit.hpp>
#include <psemek/util/to_string.hpp>

#include <jni.h>

namespace psemek::android
{

	namespace
	{

		audio::channel_ptr output_channel = std::make_shared<audio::channel>();

		struct audio_engine_impl
			: audio::engine
		{
			audio::channel_ptr output() override
			{
				return output_channel;
			}
		};

	}

}

namespace psemek::audio
{

	std::unique_ptr<engine> make_engine()
	{
		return std::make_unique<android::audio_engine_impl>();
	}

}

extern "C" int Java_psemek_app_PsemekApplication_audioFrequencyNative(JNIEnv *, jclass)
{
	return psemek::audio::frequency;
}

extern "C" int Java_psemek_app_PsemekApplication_audioGetSamples(JNIEnv * env, jclass, jfloatArray buffer, jint sampleOffset, jint sampleCount)
{
	jfloat * data = env->GetFloatArrayElements(buffer, nullptr);

	int result = 0;
	if (auto stream = psemek::android::output_channel->stream())
		result = stream->read({data + sampleOffset, sampleCount});

	std::fill(data + sampleOffset + result, data + sampleOffset + sampleCount, 0.f);

	return sampleCount;
}
