package service

import (
	"fmt"
	"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/probe"
)

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 fmt.Errorf("ProbeClientService: InitService failed %v", err)
	}

	return nil
}

func (s *ProbeClientService) StartService() error {
	if err := s.RPCClientService.StartService(); nil != err {
		return fmt.Errorf("ProbeClientService: StartService failed %v", err)
	}

	client, err := probe.New(s.HandleEncryptionKey, s.DiscoveryService)
	if nil != err {
		return fmt.Errorf("ProbeClientService: StartService failed %v", err)
	}
	s.client = client

	if err := s.client.Start(); nil != err {
		return fmt.Errorf("ProbeClientService: StartService failed %v", 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
}
