import { defineStore } from 'pinia' import { orderBy } from 'lodash-es' import type { Playlist } from '../types' export const usePlaylistStore = defineStore('playlist', { state: () => ({ playlists: [] as Playlist[], }), actions: { getPlaylist(id: string) { return this.playlists?.find(p => p.id === id) || null }, load() { return this.subsonicApi.getPlaylists().then(result => { this.playlists = orderBy(result, 'createdAt') }) }, create(name: string, tracks?: string[]) { return this.subsonicApi.createPlaylist(name, tracks).then(result => { this.playlists = orderBy(result, 'createdAt') }) }, async update({ id, name, comment, isPublic }: Playlist) { const playlist = this.playlists?.find(x => x.id === id) if (playlist) { playlist.name = name playlist.comment = comment playlist.isPublic = isPublic await this.subsonicApi.editPlaylist(id, name, comment, isPublic) } }, async addTracks(playlistId: string, trackIds: string[]) { const playlist = this.playlists?.find(x => x.id === playlistId) if (playlist) { await this.subsonicApi.addToPlaylist(playlistId, trackIds) playlist.updatedAt = new Date().toISOString() playlist.trackCount = (playlist?.trackCount || 0) + trackIds.length } }, async removeTrack(playlistId: string, index: number) { const playlist = this.playlists?.find(x => x.id === playlistId) if (playlist) { await this.subsonicApi.removeFromPlaylist(playlistId, index) playlist.updatedAt = new Date().toISOString() playlist.trackCount = (playlist?.trackCount || 0) - 1 } }, async delete(id: string) { await this.subsonicApi.deletePlaylist(id) this.playlists = this.playlists!.filter(p => p.id !== id) }, }, })