package forwarder

import (
	"context"
	"time"

	"helmet/pkg/client"
	"helmet/pkg/mlbctl"

	"github.com/spf13/cobra"
)

type CreateForwarderParams struct {
	Hostname  string
	Lport     uint32
	Dport     uint32
	Addresses []string
}
type CreateForwarderResult struct{}

func (tool *Tool) CreateForwarder(cmd *cobra.Command, args []string) {
	tool.createForwarderParams.Hostname = args[0]
	res, err := tool.createForwarder(&tool.createForwarderParams)
	printResponse(res, err)
}

func (tool *Tool) createForwarder(params *CreateForwarderParams) (*CreateForwarderResult, error) {
	var err error
	res := &CreateForwarderResult{}
	ref, err := client.NewReferer(params.Hostname)
	if err != nil {
		return res, err
	}
	authCred := client.NewAuthCredential(ref.Userinfo())
	conn, cli, err := client.NewClient(ref.Hostinfo(), authCred)
	if err != nil {
		return res, err
	}
	defer conn.Close()
	ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
	opReq := &mlbctl.CreateForwarderParams{
		Lport:        params.Lport,
		Dport:        params.Dport,
		Destinations: params.Addresses,
	}
	_, err = cli.CreateForwarder(ctx, opReq)
	if err != nil {
		return res, err
	}
	return res, err
}
