import {defineStore} from "pinia"; import type {Entity} from "~/types/entity"; import {NotificationMessage} from "~/types/notificationMessage"; import type {RuntimeConfig} from "nuxt/schema"; interface State { config: RuntimeConfig, // Notification notifications: NotificationMessage[], notificationQueue: NotificationMessage[], // Entity entity: Entity | null, } export const useLabelEditorStore = defineStore('label_editor_store', { state: (): State => ({ config: useRuntimeConfig(), // Notification notifications: [], notificationQueue: [], // Entity entity: null, }), actions: { // Notification addNotification(error: boolean, message: string) { const notification: NotificationMessage = new NotificationMessage(error, message); if (import.meta.client) { const localStoreNotification = localStorage.getItem("label_editor_notifications"); if (localStoreNotification != null) { this.notifications = JSON.parse(localStoreNotification); } } this.notificationQueue.push(notification); this.notifications.push(notification); if (import.meta.client) { localStorage.setItem('label_editor_notifications', JSON.stringify(this.notifications)); } if (notification.error) { setTimeout(() => this.removeNotification(notification.id), 5000); } else { setTimeout(() => this.removeNotification(notification.id), 2000); } }, removeNotification(id: string) { const index = this.notificationQueue.findIndex(notification => notification.id == id); if (index > -1) { this.notificationQueue.splice(index, 1); } }, getNotifications(): NotificationMessage[] { let oldNotifications: NotificationMessage[] = []; if (import.meta.client) { const localStoreNotification = localStorage.getItem("label_editor_notifications"); if (localStoreNotification != null) { oldNotifications = JSON.parse(localStoreNotification); oldNotifications.reverse(); return oldNotifications; } } return []; }, clearNotifications() { this.notifications = []; if (import.meta.client) { localStorage.setItem('label_editor_notifications', JSON.stringify(this.notifications)); } this.addNotification(false, "Benachrichtigungen gelöscht") }, // Entity async loadEntity(entityID: number) { try { const entity: Entity = await $fetch(this.config.public.url + '/entity/' + entityID, { method: 'GET', }); this.entity = entity; this.addNotification(false, 'Artikel geladen: ' + this.entity.name); } catch { this.entity = null; this.addNotification(true, 'Fehler beim laden des Artikel. ID:' + entityID); } }, async updateEntity(entity: Entity) { if (this.entity != null) { try { const entity: Entity = await $fetch(this.config.public.url + '/entity/update', { method: 'POST', body: JSON.stringify(this.entity), }); this.entity = entity; this.addNotification(false, 'Artikel "' + this.entity.name + '" aktualisiert'); } catch { this.addNotification(true, 'Fehler beim aktualisieren des Artikel: ' + this.entity.name); } } else { this.addNotification(true, 'Es ist kein Artikel ausgewählt'); } }, clearEntity() { this.entity = null; }, }, });