import { parseStringPromise } from "xml2js";
import ApiRequestManager from "./request";
import { ILibraryContents } from "./schema";

/**
 * Map a media ID such as an IMDb ID to a Plex movie key
 */
interface IMediaMap {
	[id: string]: number
}

/**
 * An interface to the a Plex server
 */
export default class Plex
{
	/**
	 * The API request manager instance
	 */
	protected requestManager: ApiRequestManager;

	/**
	 * The key for the movie library
	 */
	protected readonly KEY_MOVIES: string;

	/**
	 * The key for the TV lbirary
	 */
	protected readonly KEY_TV: string;

	/**
	 * Create a new instance of the Plex interface
	 */
	public constructor(url: string, plexToken: string, moviesKey: string, tvKey: string) {
		this.KEY_MOVIES = moviesKey;
		this.KEY_TV = tvKey;
		this.requestManager = new ApiRequestManager(url, plexToken);
	}

	/**
	 * Fetch the IMDb ID set from the Plex movies library
	 */
	public async movies() {
		let response = await this.requestManager.get(`/library/sections/${this.KEY_MOVIES}/all`);
		let library = <ILibraryContents>await parseStringPromise(response);
		let movies: IMediaMap = {};
		for (let video of library.MediaContainer.Video) {
			let imdbMatch = video.$.guid.match(/(?<=imdb\:\/\/)tt\d+/i);
			if (imdbMatch === null) {
				continue;
			}
			let imdbId = imdbMatch[0];
			let plexKey = parseInt(video.$.ratingKey);
			movies[imdbId] = plexKey;
		}
		return movies;
	}
}
