subsonic-tui/internal/tui/views/queue.go
Sagi Dayan 26e526f07e
initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-02-20 19:10:14 +02:00

131 lines
2.7 KiB
Go

package views
import (
"fmt"
"time"
"github.com/delucks/go-subsonic"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
var _ View = &queue{}
type queue struct {
view *tview.Table
currentSong int
songQueue []*subsonic.Child
playFunc func(song *subsonic.Child)
}
func NewQueue() *queue {
table := tview.NewTable()
table.SetBackgroundColor(tcell.ColorBlack)
table.SetTitle("Queue [4]")
table.SetBorder(true)
table.SetFocusFunc(func() {
table.SetBorderColor(tcell.ColorRed)
})
table.SetBlurFunc(func() {
table.SetBorderColor(tcell.ColorWhite)
})
return &queue{
view: table,
currentSong: 0,
}
}
func (q *queue) SetPlayFunc(f func(song *subsonic.Child)) {
q.playFunc = f
}
func (q *queue) PlayCurrent() {
if len(q.songQueue) > 0 {
q.playFunc(q.songQueue[q.currentSong])
}
}
func (q *queue) Add(songs ...*subsonic.Child) {
shouldStartPlaying := len(q.songQueue) == 0
q.songQueue = append(q.songQueue, songs...)
if shouldStartPlaying {
q.currentSong = 0
q.Update()
q.playFunc(songs[0])
}
}
func (q *queue) ReplaceAll(songs ...*subsonic.Child) {
q.Clear()
q.Add(songs...)
q.view.ScrollToBeginning()
}
func (q *queue) Next() {
if len(q.songQueue) > q.currentSong+1 {
q.currentSong = q.currentSong + 1
song := q.songQueue[q.currentSong]
q.playFunc(song)
}
}
func (q *queue) Prev() {
if q.currentSong > 0 {
q.currentSong = q.currentSong - 1
song := q.songQueue[q.currentSong]
q.Update()
q.playFunc(song)
}
}
func (q *queue) Clear() {
q.songQueue = []*subsonic.Child{}
q.Update()
}
func (q *queue) drawQueue() {
q.view.Clear()
list := q.view
list.SetWrapSelection(true, false)
list.SetSelectable(true, false)
for i, song := range q.songQueue {
isCurrentSong := q.currentSong == i
isPlayed := i < q.currentSong
bgColor := tcell.ColorBlack
if isCurrentSong {
bgColor = tcell.ColorDarkRed
} else if isPlayed {
bgColor = tcell.ColorDarkGray
}
num := tview.NewTableCell(fmt.Sprintf("%d", i+1)).SetTextColor(tcell.ColorYellow).SetBackgroundColor(bgColor)
title := tview.NewTableCell(song.Title).SetMaxWidth(15).SetExpansion(2).SetBackgroundColor(bgColor)
artist := tview.NewTableCell(song.Artist).SetMaxWidth(15).SetExpansion(1).SetBackgroundColor(bgColor)
d := time.Second * time.Duration(song.Duration)
duration := tview.NewTableCell(d.String()).SetAlign(tview.AlignRight).SetExpansion(1).SetBackgroundColor(bgColor)
list.SetCell(i, 0, num)
list.SetCell(i, 1, title)
list.SetCell(i, 2, artist)
list.SetCell(i, 3, duration)
}
list.SetSelectedFunc(func(row, column int) {
q.currentSong = row
q.playFunc(q.songQueue[row])
})
}
func (q *queue) Update() {
q.drawQueue()
}
func (q *queue) GetView() tview.Primitive {
return q.view
}