package main

import (
	"encoding/json"
	"fmt"
)

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

func cmdOLTsList(c *Client, args []string) error {
	o, _, err := parseListFlags("olts list", args)
	if err != nil {
		return err
	}
	items, p, raw, err := c.fetchList("/olts", 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 x OLT
			_ = json.Unmarshal(rm, &x)
			fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", x.ID, x.Name, x.Site, x.Host)
		}
		return tw.Flush()
	})
}

func cmdOLTsGet(c *Client, args []string) error {
	jsonMode, id, err := parseGetFlags("olts get", args)
	if err != nil {
		return err
	}
	var x OLT
	var raw []byte
	if err := c.get(apiPrefix+"/olts/"+pathID(id), &x, &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", x.ID, x.Name, x.Site, x.Host)
	return tw.Flush()
}
