package service

import (
	"context"
	"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"
	crc "git.loafle.net/commons/rpc-go/client"
	occp "git.loafle.net/overflow/commons-go/config/probe"
	"git.loafle.net/overflow/probe/client/probe"
	// For annotation
	_ "git.loafle.net/overflow/commons-go/core/annotation"
)

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

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

type ProbeClientService struct {
	cda.TypeAnnotation `annotation:"@overflow:RPCService()"`

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

	EncryptionKey string

	client *crc.Client
}

func (s *ProbeClientService) InitService() error {

	return nil
}

func (s *ProbeClientService) StartService() error {
	client, err := probe.New(s.HandleResponse, 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() {
	if err := s.client.Stop(context.Background()); nil != err {
		logging.Logger().Error(err)
	}

}

func (s *ProbeClientService) DestroyService() {

}

func (s *ProbeClientService) HandleResponse(method string, param string) {
	switch method {
	case occp.HTTPResponseHeaderValue_Probe_Method_EncryptionKey:
		s.EncryptionKey = param
	case occp.HTTPResponseHeaderValue_Probe_Method_Delete:
	}

}

func (s *ProbeClientService) Call(result interface{}, method string, params ...interface{}) error {
	if nil == s.client {
		return fmt.Errorf("rpc client is not valid")
	}
	return s.client.Call(result, method, params...)
}

func (s *ProbeClientService) Send(method string, params ...interface{}) error {
	if nil == s.client {
		return fmt.Errorf("rpc client is not valid")
	}
	return s.client.Send(method, params...)
}
