package service

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"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"
	sensorConfigM "git.loafle.net/overflow/overflow_commons_go/modules/sensor_config/model"
	"git.loafle.net/overflow/overflow_probes/config"
)

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

}

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

	sensorConfigs map[string]*sensorConfigM.SensorConfig
}

func (scs *SensorConfigService) Start() error {
	var (
		err error
	)

	scs.sensorConfigs = make(map[string]*sensorConfigM.SensorConfig)

	if err = scs.loadConfigAll(); nil != err {
		return err
	}

	return nil
}

func (scs *SensorConfigService) Stop(ctx context.Context) error {

	return nil
}

func (scs *SensorConfigService) 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 := scs.loadConfigDir(path.Join(configDirPath, file.Name())); nil != err {
				return err
			}
		}
	}

	return nil
}

func (scs *SensorConfigService) 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 {
			if err := scs.loadConfigDir(filePath); nil != err {
				return err
			}
		} else {
			sc, _, err := scs.loadConfigFile(filePath)
			if nil != err {
				return err
			}
			scs.sensorConfigs[file.Name()] = sc
		}
	}

	return nil
}

func (scs *SensorConfigService) loadConfigFile(filePath string) (*sensorConfigM.SensorConfig, []byte, error) {
	buf, err := ioutil.ReadFile(filePath)
	if nil != err {
		return nil, nil, err
	}

	var m = &sensorConfigM.SensorConfig{}
	if err := json.Unmarshal(buf, m); nil != err {
		return nil, nil, err
	}

	return m, buf, nil
}

func (scs *SensorConfigService) AddConfig(tempFilePath string) error {
	sc, buf, err := scs.loadConfigFile(tempFilePath)
	if nil != err {
		return err
	}

	targetPath := config.SensorConfigFilePath(sc)
	ioutil.WriteFile(targetPath, buf, 0644)

	// tempfile remove
	err = os.Remove(tempFilePath)
	if nil != err {
		return err
	}

	scs.sensorConfigs[sc.ID.String()] = sc

	return nil
}

func (scs *SensorConfigService) RemoveConfig(sensorConfigID string) error {
	sc, ok := scs.sensorConfigs[sensorConfigID]
	if !ok {
		return fmt.Errorf("Probe: SensorConfig[%s] is not exist", sensorConfigID)
	}

	targetPath := config.SensorConfigFilePath(sc)
	err := os.Remove(targetPath)
	if nil != err {
		return err
	}

	delete(scs.sensorConfigs, sensorConfigID)

	return nil
}
