#include "sierrachart.h"

class SetStudyPersistentDemoAvg
{
public:
	SetStudyPersistentDemoAvg(): Historical(true), myPrivateInt(0)
	{
		for (int i = 0; i < 10; i++)
		{
			vect.push_back(i);
		}
	}

	~SetStudyPersistentDemoAvg()
	{
	}

	bool Historical;

private:
	int myPrivateInt;
	std::vector<int> vect;
};


SCSFExport scsf_SetStudyPersistentDemoAvg(SCStudyInterfaceRef sc)
{
	SCString message;
	auto pState = static_cast<SetStudyPersistentDemoAvg*>(sc.GetPersistentPointer(1));

	SCSubgraphRef Avg = sc.Subgraph[0];

	SCInputRef Length = sc.Input[0];

	if (sc.SetDefaults)
	{
		sc.GraphName = "SetStudyPersistentDemoAvg";
		sc.StudyDescription = "SetStudyPersistentDemo Slave";
		sc.StudyVersion = 1;
		sc.GraphRegion = 0;
		sc.ValueFormat = VALUEFORMAT_INHERITED;
		sc.FreeDLL = 0; // we can't use FreeDLL with this template
		sc.AutoLoop = false;

		Avg.Name = "Avg";
		Avg.DrawStyle = DRAWSTYLE_LINE;
		Avg.LineStyle = LINESTYLE_DASH;
		Avg.PrimaryColor = COLOR_MAGENTA;

		Length.Name = "Length";
		Length.SetInt(10);
		Length.SetIntLimits(1, MAX_STUDY_LENGTH);

		return;
	}
	
	if (sc.LastCallToFunction)
	{
		// clean up
		if (pState != nullptr)
		{
			delete pState;
			pState = nullptr;
			sc.SetPersistentPointer(1, pState);
		}
		return;
	}

	bool isExternalChangeToParameter = false;
	int& length = sc.GetPersistentInt(1);
	if (length != 0 && length != Length.GetInt())
	{
		// An external study has changed this value
		Length.SetInt(length);
		isExternalChangeToParameter = true;
	}

	if (sc.IsFullRecalculation || sc.UpdateStartIndex == 0 || isExternalChangeToParameter)
	{
		// Initialize -- first call to study.
		if (pState != nullptr)
		{
			// ALWAY reinitialize the class. 
			delete pState;
			pState = nullptr;
			sc.SetPersistentPointer(1, pState);
		}
		if (pState == nullptr)
		{
			pState = static_cast<SetStudyPersistentDemoAvg*>(new SetStudyPersistentDemoAvg);
			sc.SetPersistentPointer(1, pState);
			if (pState == nullptr)
			{
				return;
			}
		}
	}

	// Now do the standard manual looping.
	int tmp = Length.GetInt();
	for (int index = sc.UpdateStartIndex; index < sc.ArraySize; ++index)
	{
		// set subgraph values
		sc.DataStartIndex = Length.GetInt() - 1;
		sc.SimpleMovAvg(sc.BaseDataIn[SC_LAST], Avg, index, Length.GetInt());
	}

	// now that we've done our first pass, we're live
	pState->Historical = false;
}

