package command

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"strings"
	"text/tabwriter"
)

var ErrHelp = errors.New("help requested")

func (n *node) PrintHelp() { _ = n.writeHelp() }

func (n *node) writeHelp() error {
	prefix := strings.Join(append(n.prefix, n.name), " ")
	var buf strings.Builder
	offset := 7 + len(prefix)
	line := offset + 14
	w := bytes.Repeat([]byte{' '}, offset+1)
	w[0] = '\n'

	for _, flag := range n.suffix {
		line += len(flag) + 1
		if line >= 80 {
			line = offset + len(flag) + 1
			buf.Write(w)
		}
		buf.WriteByte(' ')
		buf.WriteString(flag)
	}

	if _, err := fmt.Fprintf(n.out,
		"usage: %s [-h | --help]%s <command> [<args>]\n",
		prefix, &buf,
	); err != nil {
		return err
	}
	if n.child != nil {
		if _, err := fmt.Fprint(n.out, "\ncommands:\n"); err != nil {
			return err
		}
	}

	tw := tabwriter.NewWriter(n.out, 0, 1, 4, ' ', 0)
	if err := n.child.writeCommands(tw); err != nil {
		return err
	}
	if err := tw.Flush(); err != nil {
		return err
	}

	_, err := n.out.Write([]byte{'\n'})
	if err == nil {
		err = ErrHelp
	}
	return err
}

func (n *node) writeCommands(w io.Writer) error {
	if n == nil {
		return nil
	}
	if n.usage != UsageInternal {
		if _, err := fmt.Fprintf(w, "\t%s\t%s\n", n.name, n.usage); err != nil {
			return err
		}
	}
	return n.next.writeCommands(w)
}
