import { IMovieSearchInfo } from "@autoplex-api/torrent-search";
import Torrent from "../Torrent";

/**
 * Media type flags
 */
export enum MediaType {
	None    = 0x0,
	Movies  = 0x1,
	TvShows = 0x2
}

export default abstract class Provider
{
	/**
	 * Indicate what media types the provider supports
	 */
	public abstract readonly PROVIDES: MediaType;

	/**
	 * Search for movies
	 */
	public abstract searchMovie(movie: IMovieSearchInfo): Promise<Torrent[]>;

	// ---------------------------------------------------------------------------------------------

	/**
	 * Indicate if the provider is currently searching for a torrent
	 */
	protected isSearching = false;

	/**
	 * Maintain a queue of search requests
	 */
	protected searchQueue: (() => void)[] = [];

	/**
	 * Lock the search
	 */
	protected async lock() {
		if (this.isSearching) {
			await new Promise<void>(resolve => this.searchQueue.push(resolve));
		}
		this.isSearching = true;
	}

	/**
	 * Unlock the search
	 */
	protected unlock(delay: number = 0) {
		setTimeout(() => {
			let next = this.searchQueue.splice(0, 1)[0];
			if (next === undefined) {
				this.isSearching = false;
				return;
			}
			next();
		}, delay);
	}
}
