import { Writable, writable } from "svelte/store";
import { v4 as uuid } from "uuid";

export const notifications: Writable<Record<string, Notification>> = writable({});

const defaults = {
	title: "",
	dismissable: false,
	timeout: 4000,
	description: "",
	type: "error",
	onUserDismiss: () => {}
};

export interface Notification {
	title: string;
	dismissable: boolean;
	timeout: number;
	description: string;
	type: "error" | "success" | "info" | "warning";
	onUserDismiss: () => any;
	uid: string;
}

export function updateNotification(uid: string, updater: Partial<Notification>) {
	notifications.update((value) => {
		value[uid] = { ...defaults, ...value[uid], ...updater } as Notification;
		return value;
	})
}

export function addNotification(notification: Partial<Notification>): string {
	let uid = uuid();

	if (!notification.uid) {
		notification.uid = uid;
	}
	
	const object: Notification = { ...defaults, ...notification } as Notification;

	notifications.update((value) => {
		value[uid] = object;
		return value;
	})

	if (object.timeout) {
		setTimeout(() => {
			deleteNotification(uid);
		}, object.timeout);
	}

	return uid;
}

export function deleteNotification(uid: string) {
	notifications.update((value) => {
		delete value[uid];
		return value;
	})
}

export function showLinkedElement(query: string) {
	const element = document.querySelector(query);

	if (!element) {
		return;
	}

	element.classList.add("linked");
}

export function hideLinkedElement(query: string) {
	const element = document.querySelector(query);

	if (!element) {
		return;
	}

	element.classList.remove("linked");
}