#include "DeerStudio/StudioAPI/Resources.h"
#include "DeerRender/Log.h"
#include "DeerStudio/AngelScriptEngine.h"

#include "angelscript.h"
#include "scriptarray.h"
#include "scriptstdstring.h"

#include <string>

namespace Deer {
	namespace StudioAPI {
		ResourceType getResourceType(std::string& dir) {
			Path path(dir);
			std::string extension = path.extension().string();

			if (extension == ".obj" || extension == ".fbx" || extension == ".dae" ||
			    extension == ".3ds" || extension == ".ply" || extension == ".stl" ||
			    extension == ".glb" || extension == ".gltf"|| extension == ".mtl") {
				return ResourceType::MESH;
			}

			if (extension == ".glsl")
				return ResourceType::SHADER;

			if (extension == ".png")
				return ResourceType::TEXTURE;

			return ResourceType::NONE;
		};

		CScriptArray* getResourceFolders(std::string& path_s) {
			CScriptArray* array = CScriptArray::Create(AngelScriptEngine::arrayStringBaseType);

			Path path_p = Path("Resources") / Path(path_s).lexically_normal();
			try {
				for (const auto& entry : std::filesystem::directory_iterator(path_p)) {
					if (entry.is_directory()) {
						std::string s = entry.path().lexically_relative("Resources").string();

						array->Resize(array->GetSize() + 1);
						array->SetValue(array->GetSize() - 1, &s);
					}
				}
			} catch (const std::exception& e) {
				DEER_EDITOR_ENGINE_ERROR("Error in getResourceFolders(), {}", e.what());
			}

			return array;
		}

		CScriptArray* getResourceFiles(std::string& path_s) {
			CScriptArray* array = CScriptArray::Create(AngelScriptEngine::arrayStringBaseType);

			Path path_p = Path("Resources") / Path(path_s).lexically_normal();
			try {
				for (const auto& entry : std::filesystem::directory_iterator(path_p)) {
					if (entry.is_regular_file()) {
						std::string s = entry.path().lexically_relative("Resources").string();

						array->Resize(array->GetSize() + 1);
						array->SetValue(array->GetSize() - 1, &s);
					}
				}
			} catch (const std::exception& e) {
				DEER_EDITOR_ENGINE_ERROR("Error in getResourceFiles(), {}", e.what());
			}

			return array;
		}

	} // namespace StudioAPI
} // namespace Deer