#include "DeerStudio/AngelScriptEngine.h"
#include "angelscript.h"
#include "DeerRender/Log.h"
#include "DeerStudio/AngelScriptEngine/ErrorHandle.h"

namespace Deer {
	namespace AngelScriptEngine {
		Module::Module(asIScriptModule* _angelscriptModule) {
			angelscriptModule = _angelscriptModule;
			uint32_t typeCount = angelscriptModule->GetObjectTypeCount();

			for (uint32_t typeId = 0; typeId < typeCount; typeId++) {
				asITypeInfo* typeInfo = angelscriptModule->GetObjectTypeByIndex(typeId);

				if (ImplementsInterface(typeInfo, serviceBaseType)) {
					services.push_back({typeInfo});
				} else if (ImplementsInterface(typeInfo, panelBaseType)) {
					panels.push_back({typeInfo});
				}
			}
		}

		void Module::init() {
			angelscriptModule->BindAllImportedFunctions();

			if (invalidated)
				return;

			for (Service& service : services)
				service.init();

			for (Panel& panel : panels)
				panel.init();
		}

		void Module::update() {
			if (invalidated)
				return;

			for (Service& service : services)
				service.update();

			for (Panel& panel : panels)
				panel.update();
		}

		void Module::render() {
			if (invalidated)
				return;

			for (Panel& panel : panels)
				panel.render();
		}

		void Module::shutdown() {
			for (Service& service : services)
				service.shutdown();

			for (Panel& panel : panels)
				panel.shutdown();

			if (invalidated)
				return;
		}

		Module::~Module() {
			services.clear();
			panels.clear();
		}
	}; // namespace AngelScriptEngine
}; // namespace Deer