package service

import (
	"context"
	"fmt"
	"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"
	oogwc "git.loafle.net/overflow/overflow_gateway_websocket/client"
)

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

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

	oocmci.Service

	CentralClients map[string]oogwc.Client `annotation:"@Resource()"`
}

func (cs *CentralService) Start() error {
	if nil == cs.CentralClients || 0 == len(cs.CentralClients) {
		return fmt.Errorf("There is no clients of Central")
	}

	for k, client := range cs.CentralClients {
		if err := client.Connect(); nil != err {
			return fmt.Errorf("Cannot connect to client[%s] of Central %v", k, err)
		}
	}

	return nil
}

func (cs *CentralService) Stop(ctx context.Context) error {

	return nil
}

func (cs *CentralService) PutClient(entryPath string, c oogwc.Client) {
	cs.CentralClients[entryPath] = c
}

func (cs *CentralService) Call(entryPath string, result interface{}, method string, params ...interface{}) error {
	c := cs.GetClient(entryPath)
	return c.Call(result, method, params...)
}

func (cs *CentralService) Send(entryPath string, method string, params ...interface{}) error {
	c := cs.GetClient(entryPath)

	return c.Send(method, params...)
}

func (cs *CentralService) GetClient(entryPath string) oogwc.Client {
	return cs.CentralClients[entryPath]
}

func (cs *CentralService) CheckClient(entryPath string) bool {
	c, ok := cs.CentralClients[entryPath]
	if !ok || nil == c {
		return false
	}

	return true
}

func (cs *CentralService) Connect(entryPath string) error {
	// var c oogwc.Client
	// switch entryPath {
	// case oocmp.HTTPEntry_Probe:
	// 	c = oopccp.NewClient()
	// case oocmp.HTTPEntry_Data:
	// 	c = oopccd.NewClient()
	// case oocmp.HTTPEntry_File:
	// 	c = oopccf.NewClient()
	// default:
	// 	return fmt.Errorf("Gateway entry[%s] is not exist", entryPath)
	// }

	// cs.clients[entryPath] = c

	return nil
}
