package service

import (
	"context"
	"io/ioutil"
	"path"
	"reflect"

	cda "git.loafle.net/commons_go/di/annotation"
	cdr "git.loafle.net/commons_go/di/registry"
	oocmci "git.loafle.net/overflow/overflow_commons_go/modules/commons/interfaces"
	"git.loafle.net/overflow/overflow_probes/config"
)

func init() {
	cdr.RegisterType(reflect.TypeOf((*ConfigService)(nil)))

}

type ConfigService struct {
	cda.TypeAnnotation `annotation:"@overFlow:Service()"`
	oocmci.Service
}

func (cs *ConfigService) Start() error {

	return nil
}

func (cs *ConfigService) Stop(ctx context.Context) error {

	return nil
}

func (cs *ConfigService) loadConfigAll() error {
	configDirPath := config.ConfigDirPath()
	files, err := ioutil.ReadDir(configDirPath)
	if nil != err {
		return err
	}

	for _, file := range files {
		if file.IsDir() == true {
			if err := cs.loadConfigDir(path.Join(configDirPath, file.Name())); nil != err {
				return err
			}
		}
	}

	return nil
}

func (cs *ConfigService) loadConfigDir(dirPath string) error {
	files, err := ioutil.ReadDir(dirPath)
	if nil != err {
		return err
	}

	for _, file := range files {
		filePath := path.Join(dirPath, file.Name())

		if file.IsDir() == true {
			cs.loadConfigDir(filePath)
		} else {
			_, err := ioutil.ReadFile(filePath)
			if nil != err {
				return err
			}
			// var m = config_manager.Config{}
			// json.Unmarshal(b, &m)
			// c.configs[file.Name()] = &m
		}
	}

	return nil
}
