//------------------------------------------------------------------------
// Project     : VST SDK
//
// Category    : Examples
// Filename    : public.sdk/samples/vst/multiple_programchanges/source/plugcontroller.cpp
// Created by  : Steinberg, 02/2016
// Description : Plug-in Example for VST SDK 3.x using Multiple ProgramChange parameters
//
//-----------------------------------------------------------------------------
// This file is part of a Steinberg SDK. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this distribution
// and at www.steinberg.net/sdklicenses.
// No part of the SDK, including this file, may be copied, modified, propagated,
// or distributed except according to the terms contained in the LICENSE file.
//-----------------------------------------------------------------------------

#include "plugcontroller.h"
#include "plugparamids.h"

#include "public.sdk/source/vst/utility/stringconvert.h"
#include "base/source/fstreamer.h"

#include "pluginterfaces/base/futils.h"
#include "pluginterfaces/base/ibstream.h"
#include "pluginterfaces/vst/ivstcomponent.h"

namespace Steinberg {
namespace Vst {

//------------------------------------------------------------------------
// PlugController Implementation
//------------------------------------------------------------------------
tresult PLUGIN_API PlugController::initialize (FUnknown* context)
{
	tresult result = EditControllerEx1::initialize (context);
	if (result != kResultOk)
	{
		return result;
	}

	//---Create Parameters------------

	//---Bypass parameter---
	int32 stepCount = kStepCountToggle;
	ParamValue defaultVal = 0;
	int32 flags = ParameterInfo::kCanAutomate | ParameterInfo::kIsBypass;
	int32 tag = kBypassId;
	parameters.addParameter (STR ("Bypass"), nullptr, stepCount, defaultVal, flags, tag);

	//---Create top root unit with kProgramId as id for the programList
	addUnit (new Unit (STR ("Root"), kRootUnitId, kNoParentUnitId));

	//---We want here kNumSlots slots with a program change per slot
	for (int32 i = 0; i < kNumSlots; i++)
	{
		int32 kSlotUnitID = kRootUnitId + i + 1;
		int32 kProgramListId = kProgramStartId + i;

		// create a unit for the slot associated to a programList created below
		std::u16string slotName = STR ("Slot ");
		slotName += Vst::toString (i + 1);
		addUnit (new Unit (slotName.data (), kSlotUnitID, kRootUnitId, kProgramListId));

		// create the program list: here kNumProgs entries attached to the previous created
		// unit/slot
		std::u16string programListName = STR ("Bank ");
		programListName += Vst::toString (i + 1);
		auto* prgList = new ProgramList (programListName.data (), kProgramListId, kSlotUnitID);
		addProgramList (prgList);
		buildProgramlist (kProgramListId, kNumProgs);

		//---Program Change parameter---
		Parameter* prgParam = prgList->getParameter ();

		// by default this program change parameter if automatable we can overwrite this:
		prgParam->getInfo ().flags &= ~ParameterInfo::kCanAutomate;

		// add this programChange parameter to the exported parameter list
		parameters.addParameter (prgParam);
	}

	//---Gain parameter---
	parameters.addParameter (STR ("Gain"), nullptr, 0, 1.f, ParameterInfo::kCanAutomate, kGainId);

	//--- Number of Programs (per programList) ---
	parameters.addParameter (new RangeParameter (
	    STR ("Programs Count"), kProgramCountId, nullptr, kMinProgramCount, kMaxProgramCount,
	    kMaxProgramCount, kMaxProgramCount - kMinProgramCount, ParameterInfo::kNoFlags));

	return result;
}

//-----------------------------------------------------------------------------
bool PlugController::buildProgramlist (int32 programListId, int32 numProgs)
{
	if (auto prgList = getProgramList (programListId))
	{
		prgList->clearPrograms ();

		for (int32 i = 0; i < numProgs; i++)
		{
			std::u16string title = STR ("Prog ");
			title += Vst::toString (i + 1);
			prgList->addProgram (title.data ());
		}
		return true;
	}
	return false;
}

//-----------------------------------------------------------------------------
tresult PLUGIN_API PlugController::setParamNormalized (ParamID tag, ParamValue value)
{
	tresult res = EditControllerEx1::setParamNormalized (tag, value);
	if (res == kResultOk && tag >= kProgramStartId && tag < kProgramEndId) // program changes
	{
		// here we use the program value as gain...just an example
		value *= (ParamValue) (tag - kProgramStartId + 1) /
		         (ParamValue) (kProgramEndId - kProgramStartId);
		EditControllerEx1::setParamNormalized (kGainId, value);

		if (componentHandler)
			componentHandler->restartComponent (kParamValuesChanged);
	}
	else if (res == kResultOk && tag == kProgramCountId)
	{
		int32 numProgs =
		    static_cast<int32> (parameters.getParameter (kProgramCountId)->toPlain (value));
		if (mLastNumProgs != numProgs)
		{
			mLastNumProgs = numProgs;

			for (int32 i = 0; i < kNumSlots; i++)
			{
				int32 programListId = kProgramStartId + i;
				buildProgramlist (programListId, numProgs);
				notifyProgramListChange (programListId, kAllProgramInvalid);
			}
			if (componentHandler)
			{
				// kParamTitlesChanged for parameter stepCount change
				// kMidiCCAssignmentChanged for ProgramChange parameter stepCount change
				componentHandler->restartComponent (kParamTitlesChanged | kMidiCCAssignmentChanged);
			}
		}
	}
	return res;
}

//------------------------------------------------------------------------
tresult PLUGIN_API PlugController::getUnitByBus (MediaType type, BusDirection dir, int32 busIndex,
                                                 int32 channel, UnitID& unitId)
{
	if (type == kEvent && dir == kInput && busIndex == 0 && channel >= 0 && channel < kNumSlots)
	{
		unitId = kRootUnitId + channel + 1;

		return kResultTrue;
	}

	return kResultFalse;
}

//------------------------------------------------------------------------
tresult PLUGIN_API PlugController::setComponentState (IBStream* state)
{
	// we receive the current state of the component (processor part)
	// we read only the gain and bypass value...
	if (!state)
		return kResultFalse;

	IBStreamer streamer (state, kLittleEndian);

	// read the bypass
	int32 bypassState = 0;
	if (streamer.readInt32 (bypassState) == false)
		return kResultFalse;
	setParamNormalized (kBypassId, bypassState ? 1 : 0);

	// read number of program
	int32 numPrograms = 0;
	if (streamer.readInt32 (numPrograms) == false)
		return kResultFalse;

	// read the program
	for (int32 i = 0; i < numPrograms; i++)
	{
		int32 programState = 0;
		if (streamer.readInt32 (programState) == false)
			return kResultFalse;

		if (i < kNumSlots)
			EditControllerEx1::setParamNormalized (
			    kProgramStartId + i, ToNormalized<ParamValue> (programState, kNumProgs - 1));
	}

	// read the Gain param
	float savedGain = 0.f;
	if (streamer.readFloat (savedGain) == false)
		return kResultFalse;
	setParamNormalized (kGainId, savedGain);

	// read the Program count param
	uint32 savedProgramCount = 0;
	if (streamer.readInt32u (savedProgramCount) == true)
	{
		auto norm = parameters.getParameter (kProgramCountId)->toNormalized (savedProgramCount);
		setParamNormalized (kProgramCountId, norm);
	}
	return kResultOk;
}

//------------------------------------------------------------------------
} // namespace Vst
} // namespace Steinberg
