package service

import (
	"context"
	"reflect"

	cda "git.loafle.net/commons_go/di/annotation"
	cdr "git.loafle.net/commons_go/di/registry"
	"git.loafle.net/commons_go/logging"
	oocmci "git.loafle.net/overflow/overflow_commons_go/modules/commons/interfaces"
	sensorConfigM "git.loafle.net/overflow/overflow_commons_go/modules/sensor_config/model"
)

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

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

	SensorConfigService *SensorConfigService `annotation:"@Inject()"`
	ContainerService    *ContainerService    `annotation:"@Inject()"`
}

func (cs *CrawlerService) Start() error {
	sensorConfigs := cs.SensorConfigService.sensorConfigs
	if nil == sensorConfigs || 0 == len(sensorConfigs) {
		logging.Logger().Infof("Probe: There is no Sensor config")
		return nil
	}

	sortedMap := sortSensorConfigPerContainer(sensorConfigs)
	for containerName, configs := range sortedMap {
		if err := cs.ContainerService.Send(containerName, "SensorConfigService.InitConfig", configs); nil != err {
			return err
		}
	}

	return nil
}

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

	return nil
}

func (cs *CrawlerService) Install() error {
	return nil
}

func (cs *CrawlerService) Uninstall() error {
	return nil
}

func (cs *CrawlerService) Update() error {
	return nil
}

func (cs *CrawlerService) Authenticate(crawler *sensorConfigM.Crawler, target *sensorConfigM.Target) error {
	return nil
}

func sortSensorConfigPerContainer(sensorConfigMap map[string]*sensorConfigM.SensorConfig) map[string][]*sensorConfigM.SensorConfig {
	if nil == sensorConfigMap || 0 == len(sensorConfigMap) {
		return nil
	}

	m := make(map[string][]*sensorConfigM.SensorConfig)

	for _, sensorConfig := range sensorConfigMap {
		containerName := sensorConfig.Crawler.Container
		m[containerName] = append(m[containerName], sensorConfig)
	}

	return m
}
