package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

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

func sitePrefixes(s Site) string {
	if s.Attachment == nil || len(s.Attachment.NetworkPrefixes) == 0 {
		return "-"
	}
	return strings.Join(s.Attachment.NetworkPrefixes, ",")
}

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

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