package probe

import (
	cdr "git.loafle.net/commons/di-go/registry"
	logging "git.loafle.net/commons/logging-go"
	crpj "git.loafle.net/commons/rpc-go/protocol/json"
	crr "git.loafle.net/commons/rpc-go/registry"
	cssw "git.loafle.net/commons/server-go/socket/web"
	occc "git.loafle.net/overflow/commons-go/config/container"
	occp "git.loafle.net/overflow/commons-go/config/probe"
	occa "git.loafle.net/overflow/commons-go/core/annotation"
	"git.loafle.net/overflow/probe/config"
	"git.loafle.net/overflow/probe/container"
	"git.loafle.net/overflow/probe/service"
)

func New() *cssw.Server {
	onConnectChan := make(chan *container.OnConnectInfo)
	onDisconnectChan := make(chan occp.ContainerType)
	rpcServerCodec := crpj.NewServerCodec()

	cdr.RegisterResource(config.PROBE_RPC_SERVER_CODEC, rpcServerCodec)
	cdr.RegisterResource(config.PROBE_ONCONNECT_CHAN, onConnectChan)
	cdr.RegisterResource(config.PROBE_ONDISCONNECT_CHAN, onDisconnectChan)

	services, err := cdr.GetInstancesByAnnotationType(occa.RPCServiceAnnotationType)
	if nil != err {
		logging.Logger().Panic(err)
	}

	rpcRegistry := crr.NewRPCRegistry()
	rpcRegistry.RegisterServices(services...)

	cs := &ContainerServlets{}
	cs.RPCInvoker = rpcRegistry
	cs.RPCServerCodec = rpcServerCodec
	cs.OnConnectChan = onConnectChan
	cs.OnDisconnectChan = onDisconnectChan

	sh := &ServerHandlers{}
	sh.Name = "Probe"
	sh.Services = services
	sh.OrderedServices = service.OrderedServices

	sh.RegisterServlet(occc.HTTPEntry_Container, cs)

	s := &cssw.Server{
		ServerHandler: sh,
	}

	return s
}
