yattee/Model/PlaylistsModel.swift

85 lines
2.2 KiB
Swift
Raw Normal View History

2021-09-25 08:18:22 +00:00
import Foundation
import Siesta
import SwiftUI
final class PlaylistsModel: ObservableObject {
@Published var playlists = [Playlist]()
@Published var selectedPlaylistID: Playlist.ID = ""
2021-09-25 08:18:22 +00:00
2021-10-16 22:48:58 +00:00
var accounts = AccountsModel()
init(_ playlists: [Playlist] = [Playlist]()) {
self.playlists = playlists
2021-09-25 08:18:22 +00:00
}
var all: [Playlist] {
playlists.sorted { $0.title.lowercased() < $1.title.lowercased() }
}
func find(id: Playlist.ID) -> Playlist? {
playlists.first { $0.id == id }
}
var isEmpty: Bool {
playlists.isEmpty
2021-09-25 08:18:22 +00:00
}
func load(force: Bool = false, onSuccess: @escaping () -> Void = {}) {
2021-09-25 08:18:22 +00:00
let request = force ? resource.load() : resource.loadIfNeeded()
request?
.onSuccess { resource in
if let playlists: [Playlist] = resource.typedContent() {
self.playlists = playlists
if self.selectedPlaylistID.isEmpty {
self.selectPlaylist(self.all.first?.id)
}
onSuccess()
2021-09-25 08:18:22 +00:00
}
}
.onFailure { _ in
self.playlists = []
}
}
func addVideoToCurrentPlaylist(videoID: Video.ID, onSuccess: @escaping () -> Void = {}) {
2021-10-20 22:21:50 +00:00
let resource = accounts.api.playlistVideos(currentPlaylist!.id)
let body = ["videoId": videoID]
2021-10-20 22:21:50 +00:00
resource?.request(.post, json: body).onSuccess { _ in
self.load(force: true)
onSuccess()
}
}
func removeVideoFromPlaylist(videoIndexID: String, playlistID: Playlist.ID, onSuccess: @escaping () -> Void = {}) {
2021-10-20 22:21:50 +00:00
let resource = accounts.api.playlistVideo(playlistID, videoIndexID)
2021-10-20 22:21:50 +00:00
resource?.request(.delete).onSuccess { _ in
self.load(force: true)
onSuccess()
}
}
func selectPlaylist(_ id: String?) {
selectedPlaylistID = id ?? ""
}
private var resource: Resource {
2021-10-20 22:21:50 +00:00
accounts.api.playlists!
}
private var selectedPlaylist: Playlist? {
guard !selectedPlaylistID.isEmpty else {
return nil
}
return find(id: selectedPlaylistID)
}
var currentPlaylist: Playlist? {
selectedPlaylist ?? all.first
}
2021-09-25 08:18:22 +00:00
}