aboutsummaryrefslogtreecommitdiff
path: root/playlist.go
blob: 049354e0aae5ecf060843bf5039d883d89725dab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main

import (
	"container/heap"
	"muhq.space/go/wrms/llog"
)

type Playlist []*Song

func (pl Playlist) Len() int { return len(pl) }

func (pl Playlist) Less(i, j int) bool {
	return pl[i].Weight > pl[j].Weight
}

func (pl Playlist) Swap(i, j int) {
	pl[i], pl[j] = pl[j], pl[i]
	pl[i].index = i
	pl[j].index = j
}

func (pl *Playlist) Push(x any) {
	n := len(*pl)
	song := x.(*Song)
	song.index = n
	*pl = append(*pl, song)
}

func (pl *Playlist) Pop() any {
	old := *pl
	n := len(old)
	s := old[n-1]
	old[n-1] = nil // avoid memory leak
	*pl = old[0 : n-1]
	return s
}

func (pl *Playlist) PopSong() *Song {
	llog.DDebug("popping song from the playlist (%p) -> %v", pl, pl)
	if len(*pl) == 0 {
		return nil
	}

	s := heap.Pop(pl).(*Song)
	llog.DDebug("popped song %p from the playlist (%p) -> %v", s, pl, pl)
	return s
}

func (pl *Playlist) Add(s *Song) {
	heap.Push(pl, s)
	llog.DDebug("added song %p to the playlist (%p) -> %v", s, pl, pl)
}

func (pl *Playlist) Adjust(s *Song) {
	heap.Fix(pl, s.index)
	llog.DDebug("adjusting song %p in the playlist (%p) -> %v", s, pl, pl)
}

func (pl *Playlist) RemoveSong(s *Song) {
	heap.Remove(pl, s.index)
	llog.DDebug("removing song %p in the playlist (%p) -> %v", s, pl, pl)
}

func (pl *Playlist) OrderedList() []*Song {
	songs := make([]*Song, 0, pl.Len())

	cpy := make(Playlist, pl.Len())
	copy(cpy, *pl)
	llog.DDebug("copying %v returned %v", *pl, cpy)

	for cpy.Len() > 0 {
		songs = append(songs, heap.Pop(&cpy).(*Song))
	}

	llog.DDebug("ordering queue %v returned %v", pl, songs)
	return songs
}

func (pl *Playlist) applyTimeBonus(timeBonus float64) {
	for _, s := range *pl {
		s.Weight += timeBonus
		llog.DDebug("%p %v", s, s.Weight)
	}
	heap.Init(pl)
	llog.DDebug("applying time bonus to the playlist %v", *pl)
}