import { getCookie, setCookie } from '../utils/cookies' import axios from '@nextcloud/axios' import { defineStore } from 'pinia' import { generateUrl } from '@nextcloud/router' export const useSubscriptions = defineStore('subscriptions', { state: () => ({ subs: [], favs: [], }), getters: { getSubscriptions: (state) => { return state.subs }, getFavorites: (state) => { return state.favs .filter((fav) => state.subs.includes(fav.url)) .sort((fav) => fav.lastPub) }, }, actions: { async fetch() { const metrics = await axios.get( generateUrl('/apps/gpoddersync/personal_settings/metrics'), ) const subs = [...metrics.data.subscriptions].sort( (a, b) => b.listenedSeconds - a.listenedSeconds, ) this.subs = subs.map((sub) => sub.url) try { const favs = JSON.parse(getCookie('repod.favorites')) || [] this.favs = favs.map((url) => ({ url })) } catch {} }, addFavorite(url) { this.favs.push({ url }) setCookie( 'repod.favorites', JSON.stringify(this.favs.map((fav) => fav.url)), 365, ) }, editFavoriteData(url, data) { this.favs = this.favs.map((fav) => fav.url === url ? { ...fav, ...data } : fav, ) }, removeFavorite(url) { this.favs = this.favs.filter((fav) => fav.url !== url) setCookie( 'repod.favorites', JSON.stringify(this.favs.map((fav) => fav.url)), 365, ) }, }, })