package data

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

	logging "git.loafle.net/commons/logging-go"
	csc "git.loafle.net/commons/server-go/client"
	occp "git.loafle.net/overflow/commons-go/config/probe"
	"git.loafle.net/overflow/probe/client"
	"git.loafle.net/overflow/probe/config"
)

func New() (csc.Connector, error) {
	_config := config.GetConfig()
	if nil == _config {
		return nil, fmt.Errorf("Config is not available")
	}

	connector, err := client.NewConnector("Data", occp.HTTPEntry_Data)
	if nil != err {
		return nil, err
	}

	if config.Dev {
		u := url.URL{
			Scheme: "ws",
			Host:   fmt.Sprintf("%s:%d", strings.Split(_config.Central.Address, ":")[0], 19110),
		}
		u.Path = path.Join(u.Path, occp.HTTPEntry_Data)
		connector.URL = u.String()
	}

	connector.RequestHeader = func() http.Header {
		header := make(map[string][]string)
		header[occp.HTTPRequestHeaderKey_Probe_Method] = []string{occp.HTTPRequestHeaderValue_Probe_Method_Connect}
		header[occp.HTTPRequestHeaderKey_Probe_ProbeKey] = []string{*_config.Probe.Key}
		return header
	}
	connector.ResponseHandler = func(res *http.Response) {
	}
	connector.OnDisconnected = func(connector csc.Connector) {
		logging.Logger().Debugf("Client[%s] has been disconnected", connector.GetName())
	}

	return connector, nil
}
