package main

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

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

func attachmentSummary(s Service) string {
	if len(s.Attachments) == 0 {
		return "-"
	}
	parts := make([]string, 0, len(s.Attachments))
	for _, a := range s.Attachments {
		switch {
		case a.CPEMac != "":
			parts = append(parts, a.CPEMac)
		case a.CPESerial != "":
			parts = append(parts, "sn:"+a.CPESerial)
		case a.CPEIMSI != "":
			parts = append(parts, "imsi:"+a.CPEIMSI)
		case a.Username != "":
			parts = append(parts, "u:"+a.Username)
		case len(a.NetworkPrefixes) > 0:
			parts = append(parts, a.NetworkPrefixes[0])
		}
	}
	return strings.Join(parts, ",")
}

func cmdServicesList(c *Client, args []string) error {
	o, _, err := parseListFlags("services list", args)
	if err != nil {
		return err
	}
	items, p, raw, err := c.fetchList("/services", o)
	if err != nil {
		return err
	}
	return emitList(items, p, raw, o, func(items []json.RawMessage) error {
		tw := newTab()
		fmt.Fprintln(tw, "ID\tACCOUNT\tPACKAGE\tUP_KBPS\tDOWN_KBPS\tPARENT\tATTACHMENTS")
		for _, rm := range items {
			var s Service
			_ = json.Unmarshal(rm, &s)
			fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
				s.ID, s.Account, s.Package,
				fmtSpeed(s.UpSpeed), fmtSpeed(s.DownSpeed),
				s.ParentDeviceID, attachmentSummary(s))
		}
		return tw.Flush()
	})
}

func cmdServicesGet(c *Client, args []string) error {
	jsonMode, id, err := parseGetFlags("services get", args)
	if err != nil {
		return err
	}
	var s Service
	var raw []byte
	if err := c.get(apiPrefix+"/services/"+pathID(id), &s, &raw); err != nil {
		return err
	}
	if jsonMode {
		return printJSON(raw)
	}
	tw := newTab()
	fmt.Fprintln(tw, "ID\tACCOUNT\tPACKAGE\tUP_KBPS\tDOWN_KBPS\tPARENT\tATTACHMENTS")
	fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
		s.ID, s.Account, s.Package,
		fmtSpeed(s.UpSpeed), fmtSpeed(s.DownSpeed),
		s.ParentDeviceID, attachmentSummary(s))
	return tw.Flush()
}
