import store from "./store";
import { sleep } from "./util";
import websocket from "./websocket";

/**
 * Regularly update movies in the store
 */
export async function updateMoviesInStore() {
	const THROTTLE = 500;
	let lastUpdateTime = 0;

	// Cache movie ticket IDs
	let ticketIds: number[] = [];
	let updateCachedTicketIds = () => {
		ticketIds = Object.keys(store.state.movieTickets).map(parseInt);
		console.log("Ticket cache updated");
	};
	updateCachedTicketIds();

	// Listen for movie list updates
	let onMoviesUpdated: (() => void)|null = null;
	store.watch(state => state.movieTickets, () => {
		updateCachedTicketIds();
		if (onMoviesUpdated !== null) {
			onMoviesUpdated();
		}
	}, { deep: true });

	while (true) {
		// Throttle the udpates
		await sleep(THROTTLE - (Date.now() - lastUpdateTime));
		lastUpdateTime = Date.now();

		// Wait until there are movies in the list before updating
		if (ticketIds.length == 0) {
			await new Promise<void>(resolve => onMoviesUpdated = resolve);
		}

		// Get the progress of all movie tickets
		console.log("Updating movies", ticketIds.length);
		try {
			let result = await websocket.movieProgress(ticketIds);
			for (let ticketId of Object.keys(result)) {
				let tmdbId = store.state.movieTickets[<any>ticketId];
				if (tmdbId === undefined || store.state.movies[ticketId]) {
					continue;
				}
				store.state.movies[tmdbId].movie.plexLink = result[<any>ticketId].plexLink ?? null;
				store.state.movies[tmdbId].movie.progress = result[<any>ticketId].progress ?? null;
			}
		} catch(e) {
			console.error("Failed to update movies!", e);
		}
	}
}
