package modules

import (
	"agent/client/cmds"
	"agent/commons/debug"
	"agent/internal/include"
	"context"
	"sync"
)

type IModule = include.IModule

var modules = map[string]IModule{}

func Register(module IModule) {
	if module == nil {
		return
	}
	if _, ok := modules[module.Name()]; !ok {
		modules[module.Name()] = module
	}
}

func List() []IModule {
	result := make([]IModule, 0, len(modules))
	for _, item := range modules {
		result = append(result, item)
	}
	return result
}

func Load(ctx context.Context, module IModule, wg *sync.WaitGroup) (err error) {
	debug.Logf("Module.Load: %s", module.Name())

	if err = module.Init(ctx); err != nil {
		return err
	}

	commandManager := cmds.ExtractCommandManager(ctx)
	for _, cmd := range module.Commands() {
		if err = commandManager.Add(ctx, cmd); err != nil {
			return err
		}
	}

	wg.Add(1)
	go module.Run(ctx, wg)

	return nil
}
