#include "CreatePotion.h"
#include "skse64\GameObjects.h"
#include "skse64\GameData.h"
#include <string>

namespace CreatePotion {

	AlchemyItem * createPotion(StaticFunctionTag * tag, VMArray<EffectSetting*> effects, VMArray<float> magnitudes, VMArray<UInt32> areas, VMArray<UInt32> durations, UInt32 arraySize)
	{
		AlchemyItem * result = NULL;

		if (effects.Length() >= arraySize && magnitudes.Length() >= arraySize && areas.Length() >= arraySize && durations.Length() >= arraySize) {
			tArray<MagicItem::EffectItem> effectItems;
			effectItems.Allocate(arraySize);

			UInt32 count = 0;
			for (UInt32 i = 0; i < arraySize; ++i) {
				EffectSetting * magicEffect = NULL;
				effects.Get(&magicEffect, i);
				if (magicEffect) { // Only add effects that actually exist
					magnitudes.Get(&effectItems[count].magnitude, i);
					areas.Get(&effectItems[count].area, i);
					durations.Get(&effectItems[count].duration, i);
					effectItems[count].mgef = magicEffect;
					++count;
				}
			}
			effectItems.count = count; // Set count to existing count
			CALL_MEMBER_FN(PersistentFormManager::GetSingleton(), CreatePotion)(&result, &effectItems);
			Heap_Free(effectItems.entries);
		}
		else {
			_MESSAGE("Illegal arrays for creating a potion");
		}
		return result;
	}

	typedef AlchemyItem*(*CreatePotionType)(StaticFunctionTag * tag, VMArray<EffectSetting*> effects, VMArray<float> magnitudes, VMArray<UInt32> areas, VMArray<UInt32> durations);

	bool RegisterFuncs(VMClassRegistry* registry) {
		registry->RegisterFunction(
			new NativeFunction5<StaticFunctionTag, AlchemyItem *, VMArray<EffectSetting*>, VMArray<float>, VMArray<UInt32>, VMArray<UInt32>, UInt32>("CreatePotion", "EnderalLib", CreatePotion::createPotion, registry));
		return true;
	}
}