import type { Book } from '$lib/schema';
import { getContext, setContext } from 'svelte';
import { SvelteMap } from 'svelte/reactivity';

export class BookSelectionState {
	private selectedBooks = new SvelteMap<string, Book>();
	readonly selectionModeActive = $derived(this.selectedBooks.size !== 0);

	toggleSelection(book: Book) {
		const bookId = book.id.toString()
		if (this.selectedBooks.has(bookId)) 
			this.selectedBooks.delete(bookId);

		else 
			this.selectedBooks.set(bookId, book);
	}

	isSelected(id: number | string): boolean {
		return this.selectedBooks.has(id.toString());
	}

	getSelectedBooks(): Book[] {
		return Array.from(this.selectedBooks.values())
	}

	getSelectedIds(): string[] {
		return Array.from(this.selectedBooks.keys())
	}

	numSelected() {
		return this.selectedBooks.size;
	}

	selectAll(books: Book[]) {
		books.forEach((book) => {
			const bookId = book.id.toString()
			if (!this.selectedBooks.has(bookId))
				this.selectedBooks.set(bookId, book)
		});
	}

	deselectAll() {
		this.selectedBooks.clear();
	}
}

const BOOK_SELECTION_KEY = Symbol('BOOK_SELECTION');

export function setBookSelectionState() {
	return setContext(BOOK_SELECTION_KEY, new BookSelectionState());
}

export function getBookSelectionState() {
	return getContext<ReturnType<typeof setBookSelectionState>>(BOOK_SELECTION_KEY);
}
