#include "PulseLengthStatSimulationDataGenerator.h"
#include "PulseLengthStatAnalyzerSettings.h"
#include <AnalyzerHelpers.h>

PulseLengthStatSimulationDataGenerator::PulseLengthStatSimulationDataGenerator()
{
}

PulseLengthStatSimulationDataGenerator::~PulseLengthStatSimulationDataGenerator()
{
}

void PulseLengthStatSimulationDataGenerator::Initialize(U32 simulation_sample_rate, PulseLengthStatAnalyzerSettings* settings)
{
	mSimulationSampleRateHz = simulation_sample_rate;
	mSettings = settings;

	mSimChannel.SetChannel(mSettings->mInputChannel);
	mSimChannel.SetSampleRate(simulation_sample_rate);
	mSimChannel.SetInitialBitState(BIT_HIGH);
}

void PulseLengthStatSimulationDataGenerator::EmitIdle(U32 samples)
{
	mSimChannel.Advance(samples);
}

void PulseLengthStatSimulationDataGenerator::EmitLow(U32 samples)
{
	mSimChannel.TransitionIfNeeded(BIT_LOW);
	mSimChannel.Advance(samples);
}

void PulseLengthStatSimulationDataGenerator::EmitHigh(U32 samples)
{
	mSimChannel.TransitionIfNeeded(BIT_HIGH);
	mSimChannel.Advance(samples);
}

U32 PulseLengthStatSimulationDataGenerator::GenerateSimulationData(U64 largest_sample_requested, U32 sample_rate,
																   SimulationChannelDescriptor** simulation_channel)
{
	const U64 adjusted_largest_sample_requested =
		AnalyzerHelpers::AdjustSimulationTargetSample(largest_sample_requested, sample_rate, mSimulationSampleRateHz);

	while (mSimChannel.GetCurrentSampleNumber() < adjusted_largest_sample_requested)
	{
		const U32 us_to_samples = mSimulationSampleRateHz / 1000000;
		if (us_to_samples == 0)
			break;

		EmitIdle(500 * us_to_samples);
		EmitLow(4500 * us_to_samples);
		EmitHigh(4500 * us_to_samples);
		EmitLow(4500 * us_to_samples);
		EmitHigh(4500 * us_to_samples);
		EmitLow(560 * us_to_samples);
		EmitHigh(560 * us_to_samples);
		EmitLow(560 * us_to_samples);
		EmitHigh(20000 * us_to_samples);
	}

	*simulation_channel = &mSimChannel;
	return 1;
}
