package central

import (
	"fmt"
	"net/url"
	"path"

	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"
	csswc "git.loafle.net/commons/server-go/socket/web/client"
	"git.loafle.net/overflow/probe/config"
)

func newConnector(name string, entryPath string) (*csswc.Connectors, error) {
	config := config.GetConfig()
	if nil == config {
		return nil, fmt.Errorf("Config is not available")
	}

	u := url.URL{
		Scheme: "ws",
		Host:   config.Central.Address,
	}
	u.Path = path.Join(u.Path, entryPath)

	_connector := config.Central.Connector.Clone()
	connector, ok := _connector.(*csswc.Connectors)
	if !ok {
		return nil, fmt.Errorf("Cannot convert to Connectors type")
	}

	connector.Name = name
	connector.URL = u.String()

	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,
	}
}
