1package commands
2
3import (
4	"fmt"
5
6	"github.com/ambientsound/visp/log"
7	"github.com/ambientsound/visp/spotify/tracklist"
8	"github.com/zmb3/spotify"
9
10	"github.com/ambientsound/visp/api"
11)
12
13// Add plays songs in the MPD playlist.
14type Add struct {
15	command
16	api       api.API
17	client    *spotify.Client
18	tracklist *spotify_tracklist.List
19}
20
21// NewAdd returns Add.
22func NewAdd(api api.API) Command {
23	return &Add{
24		api: api,
25	}
26}
27
28// Parse implements Command.
29func (cmd *Add) Parse() error {
30	return cmd.ParseEnd()
31}
32
33// Exec implements Command.
34func (cmd *Add) Exec() error {
35	var err error
36
37	cmd.tracklist = cmd.api.Tracklist()
38	cmd.client, err = cmd.api.Spotify()
39
40	if err != nil {
41		return err
42	}
43
44	if cmd.tracklist == nil {
45		return fmt.Errorf("cannot add to queue: not in a track list")
46	}
47
48	selection := cmd.tracklist.Selection()
49	if selection.Len() == 0 {
50		return fmt.Errorf("cannot add to queue: no selection")
51	}
52
53	// Allow command to deselect tracks in visual selection that were added to the queue.
54	// In case of a queue add failure, it is desirable to still select the tracks that failed
55	// to be added.
56	cmd.tracklist.CommitVisualSelection()
57	cmd.tracklist.DisableVisualSelection()
58
59	for i, track := range selection.Tracks() {
60		err := cmd.client.QueueSong(track.ID)
61		if err != nil {
62			return err
63		}
64		log.Infof("Added %s to queue.", track.String())
65		cmd.tracklist.SetSelected(i, false)
66	}
67
68	return nil
69}
70