import importlib
import os
from importlib import util

from libs.spk_v.api import SPK5_API


class SPK5Loader:
    def __init__(self, api : SPK5_API, task_dir):
        self.loaded_modules = {}
        self.osa = api.osa
        self.api = api
        self.autoload = False
        self.task_dir = task_dir

    @staticmethod
    def dynamic_import(module_name, path):
        path = os.path.join(path)
        module_spec = importlib.util.spec_from_file_location(module_name, path)
        module = importlib.util.module_from_spec(module_spec)
        module_spec.loader.exec_module(module)
        return module

    def load(self, module_name, path):
        if self.loaded_modules.get(module_name) is not None:
            self.osa.log.w(f'Module {module_name} The module was already loaded earlier, skipping...')
            return self.loaded_modules.get(module_name)

        m = self.dynamic_import(module_name, f'{self.task_dir}/{path}')

        if m is not None:
            self.loaded_modules[module_name] = m
            return m

    def get(self, module_name):
        m = self.loaded_modules[module_name]
        if m is None and (not self.autoload):
            self.osa.log.f(f'Module with name {module_name} not loaded!')
        return m

    def init_modules(self):
        for m in self.loaded_modules.values():
            print(m)
            m.mod_init(self.api)

    def run_module(self, module_name, args):
        m = self.get(module_name)
        m.mod_run(args)

