package speaker

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

type Client struct {
	ServerURL string
}

func (c *Client) send(path string) error {
	url := fmt.Sprintf("%s%s", c.ServerURL, path)
	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		panic(err)
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	if res.StatusCode != 200 {
		b, err := io.ReadAll(res.Body)
		if err != nil {
			panic(err)
		}
		if len(b) > 0 {
			return fmt.Errorf("%s: %s", res.Status, strings.TrimSpace(string(b)))
		}
		return fmt.Errorf("%s", res.Status)
	}
	return nil
}

func (c *Client) Stop() error {
	return c.send("/stop")
}
func (c *Client) PlayDing() error {
	return c.send("/play/ding")
}
func (c *Client) PlayAlert() error {
	return c.send("/play/alert")
}
func (c *Client) PlayYoutube(id string) error {
	return c.send(fmt.Sprintf("/play/youtube?id=%s", id))
}
func (c *Client) PlaySoundcloud(id string) error {
	return c.send(fmt.Sprintf("/play/soundcloud?id=%s", id))
}
