#include "sierrachart.h"

class SetStudyPersistentDemo
{
public:
	SetStudyPersistentDemo(): Historical(true), myPrivateInt(0)
	{
		for (int i = 0; i < 10; i++)
		{
			vect.push_back(i);
		}
	}

	~SetStudyPersistentDemo()
	{
	}

	bool Historical;

private:
	int myPrivateInt;
	std::vector<int> vect;
};


SCSFExport scsf_SetStudyPersistentDemo(SCStudyInterfaceRef sc)
{
	SCString message;
	auto pState = static_cast<SetStudyPersistentDemo*>(sc.GetPersistentPointer(1));

	SCInputRef OtherStudy = sc.Input[0];
	SCInputRef LengthOtherStudy = sc.Input[1];

		if (sc.SetDefaults)
	{
		sc.GraphName = "SetStudyPersistentDemo";
		sc.StudyDescription = "SetStudyPersistentDemo Master";
		sc.StudyVersion = 1;
		sc.GraphRegion = 0;
		sc.ValueFormat = VALUEFORMAT_INHERITED;
		sc.FreeDLL = 0; // we can't use FreeDLL with this template
		sc.AutoLoop = false;  
		
		OtherStudy.Name = "SetStudyPersistentDemoAvg Study";
		OtherStudy.SetStudyID(1);

		LengthOtherStudy.Name = "LengthOtherStudy";
		LengthOtherStudy.SetInt(20);
		LengthOtherStudy.SetIntLimits(1, MAX_STUDY_LENGTH);

		return;
	}
	
	if (sc.LastCallToFunction)
	{
		// clean up
		if (pState != nullptr)
		{
			delete pState;
			pState = nullptr;
			sc.SetPersistentPointer(1, pState);
		}
		return;
	}


	if (sc.IsFullRecalculation || sc.UpdateStartIndex == 0)
	{
		// 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<SetStudyPersistentDemo*>(new SetStudyPersistentDemo);
			sc.SetPersistentPointer(1, pState);
			if (pState == nullptr)
			{
				return;
			}
		}

		const int otherStudyId = OtherStudy.GetStudyID();
		const int length = sc.GetStudyPersistentIntFromChart(sc.ChartNumber, otherStudyId, 1);
		if (length != LengthOtherStudy.GetInt())
		{
			sc.SetStudyPersistentIntFromChart(sc.ChartNumber, otherStudyId, 1, LengthOtherStudy.GetInt());
			sc.FlagFullRecalculate = 1;
		}
		if (sc.FlagFullRecalculate)
		{
			return;
		}
	}

}

