package service

import (
	"encoding/json"
	"fmt"
	"reflect"

	cda "git.loafle.net/commons/di-go/annotation"
	cdr "git.loafle.net/commons/di-go/registry"
	logging "git.loafle.net/commons/logging-go"
	csc "git.loafle.net/commons/server-go/client"
	ocmd "git.loafle.net/overflow/commons-go/model/data"
	ocsp "git.loafle.net/overflow/commons-go/service/probe"
	"git.loafle.net/overflow/probe/client/data"

	// For annotation
	_ "git.loafle.net/overflow/commons-go/core/annotation"
)

var MetricServiceType = reflect.TypeOf((*MetricService)(nil))

func init() {
	cdr.RegisterType(MetricServiceType)
}

type MetricService struct {
	ocsp.MetricService

	cda.TypeAnnotation `annotation:"@overflow:RPCService()"`

	connector csc.Connector
	readChan  <-chan []byte
	writeChan chan<- []byte
}

func (s *MetricService) InitService() error {

	return nil
}

func (s *MetricService) StartService() error {
	connector, err := data.New()
	if nil != err {
		return fmt.Errorf("MetricService: StartService failed %v", err)
	}
	err = connector.Validate()
	if nil != err {
		return fmt.Errorf("MetricService: StartService failed %v", err)
	}

	s.connector = connector

	readChan, writeChan, err := s.connector.Connect()
	if nil != err {
		return fmt.Errorf("MetricService: StartService failed %v", err)
	}
	s.readChan = readChan
	s.writeChan = writeChan

	return nil
}

func (s *MetricService) StopService() {
	if err := s.connector.Disconnect(); nil != err {
		logging.Logger().Error(err)
	}
}

func (s *MetricService) DestroyService() {

}

func (s *MetricService) Send(metric *ocmd.Metric) error {
	buff, err := json.Marshal(metric)
	if nil != err {
		return err
	}
	// s.MetricService.Send("MS", sensorConfigID, metric)
	// logging.Logger().Debugf("Metric: %v", metric)
	s.writeChan <- buff

	return nil
}
