package k8s

import (
	"context"
	"fmt"
	"strings"

	"github.com/pingcap/errors"
	"github.com/pingcap/log"
	"k8s.io/apimachinery/pkg/util/net"
	"k8s.io/client-go/kubernetes"
	restclient "k8s.io/client-go/rest"
)

// http client use kubernetes proxy to request.
type HttpLinkByKubeProxy struct {
	cli  kubernetes.Interface
	ns   string
	name string
	port string
	ctx  context.Context
}

func NewHttpLinkByKubeProxy(ctx context.Context, cli kubernetes.Interface, ns, name, port string) *HttpLinkByKubeProxy {
	link := &HttpLinkByKubeProxy{
		cli:  cli,
		ns:   ns,
		name: name,
		port: port,
		ctx:  ctx,
	}
	return link
}

func (g *HttpLinkByKubeProxy) Get(path string) ([]byte, error) {
	resp := g.cli.CoreV1().Services(g.ns).ProxyGet("https", g.name, g.port, path, nil)

	body, err := resp.DoRaw(g.ctx)

	if err != nil {
		return nil, errors.AddStack(err)
	}
	return body, nil
}

func (g *HttpLinkByKubeProxy) Post(path string, data interface{}) ([]byte, error) {
	request := g.makeCreateTaskRequest(path, fmt.Sprint(data))
	body, err := request.DoRaw(g.ctx)
	if err != nil {
		log.S().Errorf("create Tasks error %s,cfg: %s", err, data)
		return nil, err
	}

	return body, nil
}

func (g *HttpLinkByKubeProxy) makeCreateTaskRequest(api string, cfg string) restclient.ResponseWrapper {
	request := g.cli.CoreV1().RESTClient().Post().
		Namespace(g.ns).
		Resource("services").
		SubResource("proxy").
		Name(net.JoinSchemeNamePort("https", g.name, g.port)).
		Suffix(api).Body(strings.NewReader(cfg))
	return request
}
