import { SOCKET_PATH } from "@autoplex-api/plex";
import { PlexMovie } from "@autoplex/database";
import { IpcServerService } from "@autoplex/ipc";
import { plexMediaUrl } from "../utils";

export default class IpcInterface extends IpcServerService
{
	/**
	 * The name of the service
	 */
	public readonly NAME = "IPC Interface";

	/**
	 * The path to the socket file
	 */
	public readonly SOCKET_PATH = SOCKET_PATH;

	/**
	 * Install the message handlers
	 */
	protected installMessageHandlers() {
		this.addMessageHandler("movie_links", this.movieLinks);
	}

	/**
	 * Fetch links to Plex media items
	 */
	protected async movieLinks(tmdbIds: (number|string)[]) {
		let plexKeys = await Promise.all(tmdbIds.map(
			tmdbId => PlexMovie.findPlexKey(tmdbId)
		));
		return tmdbIds.reduce((o, k, i) => ({
			...o,
			[k]: (plexKeys[i] !== null ? plexMediaUrl(plexKeys[i]!) : null)
		}), {});
	}
}
