package service

import (
	"reflect"

	cda "git.loafle.net/commons/di-go/annotation"
	cdr "git.loafle.net/commons/di-go/registry"

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

var ProbeClientServiceType = reflect.TypeOf((*ProbeClientService)(nil))

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

type ProbeClientService struct {
	RPCClientService

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

	DiscoveryService *DiscoveryService `annotation:"@Inject()"`

	EncryptionKey string
}

func (s *ProbeClientService) InitService() error {
	if err := s.RPCClientService.InitService(); nil != err {
		return err
	}

	return nil
}

func (s *ProbeClientService) StartService() error {
	if err := s.RPCClientService.StartService(); nil != err {
		return err
	}

	client, err := central.NewProbe(s.HandleEncryptionKey, s.DiscoveryService)
	if nil != err {
		return err
	}
	s.client = client

	if err := s.client.Start(); nil != err {
		return err
	}

	return nil
}

func (s *ProbeClientService) StopService() {
	s.RPCClientService.StopService()
}

func (s *ProbeClientService) DestroyService() {
	s.RPCClientService.DestroyService()
}

func (s *ProbeClientService) HandleEncryptionKey(encryptionKey string) {
	s.EncryptionKey = encryptionKey
}
