package app

import (
	"common/log"
	"fmt"
	"github.com/judwhite/go-svc"
	"robot/config"
)

type Program struct {
	moduleList []Module // 模块列表
}

type Module interface {
	init() error
	start() error
	stop() error
}

func (p *Program) Init(_ svc.Environment) error {
	p.moduleList = append(p.moduleList, &ModuleBase{})
	p.moduleList = append(p.moduleList, &ModuleWebsocket{})
	p.moduleList = append(p.moduleList, &ModulePprof{})

	for _, module := range p.moduleList {
		if err := module.init(); err != nil {
			return err
		}
	}
	log.Infof(fmt.Sprintf("%v Init successful...", config.Get().App.Name))
	return nil
}

func (p *Program) Start() error {
	for _, module := range p.moduleList {
		if err := module.start(); err != nil {
			return err
		}
	}

	log.Infof(fmt.Sprintf("%v Start successful...", config.Get().App.Name))
	return nil
}

func (p *Program) Stop() error {
	for i := len(p.moduleList) - 1; i >= 0; i-- {
		module := p.moduleList[i]
		if err := module.stop(); err != nil {
			log.Errorf("module stop error: %v", err)
		}
	}

	log.Infof(fmt.Sprintf("%v Stop successful...", config.Get().App.Name))
	return nil
}
