import { MovieTicket } from "@autoplex/database";
import { IActiveMovieTicket } from "./schema";

interface ITicketMap {
	[ticketId: number]: IActiveMovieTicket
}

export default class MovieTicketMap
{
	/**
	 * Store a mapping from movie ticket ID to movie ticket
	 */
	protected tickets: ITicketMap = {};

	/**
	 * Store a mapping of tickets by TMDb ID
	 */
	protected tmdbIdMap: { [tmdbId: string]: number } = {};

	/**
	 * Add a ticket to the map
	 */
	public add(ticket: MovieTicket) {
		this.tickets[ticket.id] = {
			ticket,
			progress: 0.0,
			state: undefined
		};
		this.tmdbIdMap[ticket.tmdbId] = ticket.id;
		return this.tickets[ticket.id];
	}

	/**
	 * Check if the given TMDb ID exists in the map
	 */
	public hasMovie(tmdbId: number|string) {
		return tmdbId in this.tmdbIdMap;
	}

	/**
	 * Remove a ticket from the map
	 */
	public remove(ticket: number|MovieTicket) {
		let ticketId = (typeof ticket === "number") ? ticket : ticket.id;
		let activeTicket = this.tickets[ticketId];
		delete this.tmdbIdMap[activeTicket.ticket.tmdbId];
		delete this.tickets[ticketId];
	}
}
