
#ifndef CMODULELOADER_HPP
#define CMODULELOADER_HPP
#include <dlfcn.h>
#include <iostream>
#include <filesystem>
#include "../Configuration/CConfiguration.hpp"
namespace CosmicCore
{
    class CModuleLoader {
    public:
        static std::vector<void*> handles;

        static int loadAll(){
            std::filesystem::directory_entry rootDir(CConfiguration::moduleConfiguration.getModulesDirectory());
            if(rootDir.exists() && rootDir.is_directory())
            {
                std::filesystem::directory_iterator iteR(rootDir);
                for(auto fileEntry : iteR)
                {
                    if(fileEntry.is_regular_file())
                    {
                        auto ext = fileEntry.path().extension().string();
                        if(ext == ".so")
                        {
                            if(load(fileEntry.path()))
                                return 1;
                        }
                    }
                }
            }
            return 0;
        }

        static int load(std::filesystem::path moduleFile){
            void* handle = dlopen(moduleFile.c_str(), RTLD_LAZY);
            if (!handle) {
                std::cerr << "Failed to load shared library: " << dlerror() << std::endl;
                return 1;
            }
            // Get the registration function
            typedef void (*RegisterModuleFunc)();
            auto registerModule = (RegisterModuleFunc)dlsym(handle, "registerModule");
            if (!registerModule) {
                std::cerr << "Failed to find registration function: " << dlerror() << std::endl;
                dlclose(handle);
                return 1;
            }

            // Register the components
            registerModule();
            handles.emplace_back(handle);
            return 0;
        }

        static int releaseAll()
        {
            for(auto handle : handles)
            {
                dlclose(handle);
            }
            return 0;
        }
    };
}
#endif
