#include "IrFoxSimulationDataGenerator.h"
#include "IrFoxAnalyzerSettings.h"
#include <AnalyzerHelpers.h>

IrFoxSimulationDataGenerator::IrFoxSimulationDataGenerator()
{
}

IrFoxSimulationDataGenerator::~IrFoxSimulationDataGenerator()
{
}

void IrFoxSimulationDataGenerator::Initialize(U32 simulation_sample_rate, IrFoxAnalyzerSettings* settings)
{
	mSimulationSampleRateHz = simulation_sample_rate;
	mSettings = settings;

	mIrSimulationData.SetChannel(mSettings->mInputChannel);
	mIrSimulationData.SetSampleRate(simulation_sample_rate);
	// Как у «покоя» на выходе TSOP: линия подтянута вверх
	mIrSimulationData.SetInitialBitState(BIT_HIGH);
}

void IrFoxSimulationDataGenerator::EmitIdle(U32 samples)
{
	mIrSimulationData.Advance(samples);
}

void IrFoxSimulationDataGenerator::EmitLow(U32 samples)
{
	mIrSimulationData.TransitionIfNeeded(BIT_LOW);
	mIrSimulationData.Advance(samples);
}

void IrFoxSimulationDataGenerator::EmitHigh(U32 samples)
{
	mIrSimulationData.TransitionIfNeeded(BIT_HIGH);
	mIrSimulationData.Advance(samples);
}

U32 IrFoxSimulationDataGenerator::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 (mIrSimulationData.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 = &mIrSimulationData;
	return 1;
}
