package forwarder

import (
	"context"
	"time"

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

	"github.com/spf13/cobra"
)

type ListForwardersParams struct {
	Hostname string
}
type ListForwardersResult struct {
	Forwarders []*mlbctl.Forwarder `json:"forwarders,omitempty"`
}

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

func (tool *Tool) listForwarders(params *ListForwardersParams) (*ListForwardersResult, error) {
	var err error
	res := &ListForwardersResult{}
	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.ListForwardersParams{}
	opRes, err := cli.ListForwarders(ctx, opReq)
	if err != nil {
		return res, err
	}
	res.Forwarders = opRes.Forwarders
	return res, err
}
