65 lines
2.0 KiB
Swift
65 lines
2.0 KiB
Swift
//
|
|
// FavouritesManager.swift
|
|
// meterios
|
|
//
|
|
// (c) 2025 Martin "maride" Dessauer
|
|
//
|
|
|
|
import Foundation
|
|
import SwiftUI
|
|
|
|
class FavouritesManager {
|
|
// default contains a ready-to-use instance of FavouritesManager.
|
|
// Not that it would make sense to have multiple instances anyway.
|
|
static public var `default` = FavouritesManager()
|
|
|
|
// favourites contain the list of drink IDs marked as favourites
|
|
private var favourites: Array<Int>
|
|
|
|
init() {
|
|
self.favourites = FavouritesManager.readFromRaw()
|
|
}
|
|
|
|
// readFromRaw reads the current favourites from the stored string and transforms it to a handy Int Array
|
|
static private func readFromRaw() -> Array<Int> {
|
|
@AppStorage("favourites") var favs = ""
|
|
return favs.split(separator: ";").map({ Int($0)! })
|
|
}
|
|
|
|
// writeToRaw writes the current favourites to the AppStorage as String
|
|
private func writeToRaw() {
|
|
@AppStorage("favourites") var favs = ""
|
|
let strFavs: Array<String> = self.favourites.map({ String($0) })
|
|
favs = strFavs.joined(separator: ";")
|
|
}
|
|
|
|
// IsFavourite returns true if the given drink ID is a favourite
|
|
func IsFavourite(_ drinkID: Int) -> Bool {
|
|
return favourites.contains(drinkID)
|
|
}
|
|
|
|
// AddFavourite adds the given drink ID to the list of favourites
|
|
func AddFavourite(_ drinkID: Int) {
|
|
favourites.append(drinkID)
|
|
writeToRaw()
|
|
}
|
|
|
|
// RemoveFavourite removes the given drink ID from the favourites list
|
|
func RemoveFavourite(_ drinkID: Int) {
|
|
let index = favourites.firstIndex(where: { $0 == drinkID })
|
|
if index != nil {
|
|
favourites.remove(at: index!)
|
|
}
|
|
writeToRaw()
|
|
}
|
|
|
|
// SetFavourite sets if the given drink ID is a favourite
|
|
func SetFavourite(drinkID: Int, shouldBeFavourite: Bool) {
|
|
if IsFavourite(drinkID) && !shouldBeFavourite {
|
|
RemoveFavourite(drinkID)
|
|
} else if !IsFavourite(drinkID) && shouldBeFavourite {
|
|
AddFavourite(drinkID)
|
|
}
|
|
}
|
|
}
|