package container

import (
	"fmt"

	logging "git.loafle.net/commons/logging-go"
	crc "git.loafle.net/commons/rpc-go/client"
	crpj "git.loafle.net/commons/rpc-go/protocol/json"
	crr "git.loafle.net/commons/rpc-go/registry"
	csc "git.loafle.net/commons/server-go/client"
	cssnc "git.loafle.net/commons/server-go/socket/net/client"
	occp "git.loafle.net/overflow/commons-go/config/probe"
)

func newConnector(name string, port int) (*cssnc.Connectors, error) {
	connector := &cssnc.Connectors{
		Network: "tcp4",
		Address: fmt.Sprintf("127.0.0.1:%d", port),
	}
	connector.ReconnectInterval = 5
	connector.ReconnectTryTime = 2
	connector.MaxMessageSize = 4096
	connector.ReadBufferSize = 4096
	connector.WriteBufferSize = 4096
	connector.PongTimeout = 60
	connector.PingTimeout = 10
	connector.PingPeriod = 9
	connector.Name = name

	connector.OnDisconnected = func(connector csc.Connector) {
		logging.Logger().Debugf("Client[%s] has been disconnected", connector.GetName())
	}

	return connector, nil
}

func newClient(name string, connector csc.Connector, services []interface{}) *crc.Client {
	codec := crpj.NewClientCodec()

	var rpcRegistry crr.RPCRegistry
	if nil != services && 0 < len(services) {
		rpcRegistry = crr.NewRPCRegistry()
		rpcRegistry.RegisterServices(services...)
	}

	return &crc.Client{
		Connector:  connector,
		Codec:      codec,
		RPCInvoker: rpcRegistry,
		Name:       name,
	}
}

func NewClient(containerType occp.ContainerType, port int, services []interface{}) (*crc.Client, error) {
	connector, err := newConnector(containerType.String(), port)
	if nil != err {
		return nil, err
	}

	return newClient(containerType.String(), connector, services), nil
}
