package main

import (
	"encoding/json"
	"fmt"
)

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

func cmdPackagesList(c *Client, args []string) error {
	o, _, err := parseListFlags("packages list", args)
	if err != nil {
		return err
	}
	items, p, raw, err := c.fetchList("/packages", o)
	if err != nil {
		return err
	}
	return emitList(items, p, raw, o, func(items []json.RawMessage) error {
		tw := newTab()
		fmt.Fprintln(tw, "ID\tNAME\tUP_KBPS\tDOWN_KBPS")
		for _, rm := range items {
			var pk Package
			_ = json.Unmarshal(rm, &pk)
			fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", pk.ID, pk.Name, fmtSpeed(pk.UpSpeed), fmtSpeed(pk.DownSpeed))
		}
		return tw.Flush()
	})
}

func cmdPackagesGet(c *Client, args []string) error {
	jsonMode, id, err := parseGetFlags("packages get", args)
	if err != nil {
		return err
	}
	var pk Package
	var raw []byte
	if err := c.get(apiPrefix+"/packages/"+pathID(id), &pk, &raw); err != nil {
		return err
	}
	if jsonMode {
		return printJSON(raw)
	}
	tw := newTab()
	fmt.Fprintln(tw, "ID\tNAME\tUP_KBPS\tDOWN_KBPS")
	fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", pk.ID, pk.Name, fmtSpeed(pk.UpSpeed), fmtSpeed(pk.DownSpeed))
	return tw.Flush()
}
