package probe

import (
	"fmt"
	"net/http"

	logging "git.loafle.net/commons/logging-go"
	crc "git.loafle.net/commons/rpc-go/client"
	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(responseHandler func(method string, param string), services ...interface{}) (*crc.Client, error) {
	config := config.GetConfig()
	if nil == config {
		return nil, fmt.Errorf("Config is not available")
	}

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

	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) {
		responseMethod := res.Header.Get(occp.HTTPResponseHeaderKey_Probe_Method)
		responseMethodParam := res.Header.Get(occp.HTTPResponseHeaderKey_Probe_Method_Param)

		if nil != responseHandler {
			responseHandler(responseMethod, responseMethodParam)
		}
	}

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

	return client.New("Probe", connector, services), nil
}
