package main

import (
	"encoding/json"
	"fmt"
)

func cmdRouters(args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("routers: expected 'list' or 'get'")
	}
	c, err := NewClient()
	if err != nil {
		return err
	}
	switch args[0] {
	case "list", "ls":
		return cmdRoutersList(c, args[1:])
	case "get":
		return cmdRoutersGet(c, args[1:])
	default:
		return fmt.Errorf("routers: unknown verb %q (want: list, get)", args[0])
	}
}

func cmdRoutersList(c *Client, args []string) error {
	o, _, err := parseListFlags("routers list", args)
	if err != nil {
		return err
	}
	items, p, raw, err := c.fetchList("/routers", o)
	if err != nil {
		return err
	}
	return emitList(items, p, raw, o, func(items []json.RawMessage) error {
		tw := newTab()
		fmt.Fprintln(tw, "ID\tNAME\tSITE\tHOST")
		for _, rm := range items {
			var r Router
			_ = json.Unmarshal(rm, &r)
			fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", r.ID, r.Name, r.Site, r.Host)
		}
		return tw.Flush()
	})
}

func cmdRoutersGet(c *Client, args []string) error {
	jsonMode, id, err := parseGetFlags("routers get", args)
	if err != nil {
		return err
	}
	var r Router
	var raw []byte
	if err := c.get(apiPrefix+"/routers/"+pathID(id), &r, &raw); err != nil {
		return err
	}
	if jsonMode {
		return printJSON(raw)
	}
	tw := newTab()
	fmt.Fprintln(tw, "ID\tNAME\tSITE\tHOST")
	fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", r.ID, r.Name, r.Site, r.Host)
	return tw.Flush()
}
