import { IpcClient as Plex } from "@autoplex-api/plex";
import { IMovie, IpcClient as Search } from "@autoplex-api/search";
import { ErrorType } from "@autoplex-api/manager";
import { MovieInfo, MovieTicket, User } from "@autoplex/database";
import { InternalService, Microservice } from "@autoplex/microservice";
import MovieTicketMap from "./MovieTicketMap";


export default class TicketManager extends InternalService
{
	/**
	 * The name of the service
	 */
	public readonly NAME = "Ticket Manager";

	/**
	 * Store all active movie tickets
	 */
	protected activeMovieTickets: MovieTicketMap = new MovieTicketMap();

	/**
	 * Store a reference to the Plex service
	 */
	protected plex!: Plex;

	/**
	 * Store a reference to the Search service
	 */
	protected search!: Search;

	/**
	 * Link to other services
	 */
	public override link(app: Microservice) {
		this.plex   = app.service<Plex>("Plex");
		this.search = app.service<Search>("Search");
	}

	/**
	 * Create a new movie request ticket
	 */
	public async createMovieTicket(userId: number, tmdbId: number) {
		if (this.activeMovieTickets.hasMovie(tmdbId) || await this.plex.hasMovie(tmdbId)) {
			throw new Error(ErrorType.MovieTicketConflict);
		}
		let movie = await this.search.movieDetails(tmdbId);
		if (!movie) {
			throw new Error(ErrorType.MovieNotFound);
		}
		let info = new MovieInfo();
		info.originalLanguage = movie.originalLanguage;
		info.originalTitle = movie.originalTitle;
		info.overview = movie.overview;
		info.posterPath = movie.posterPath;
		info.backdropPath = movie.backdropPath;
		info.releaseDate = movie.releaseDate;
		info.runtime = movie.runtime;
		await info.save();

		let ticket = new MovieTicket();
		ticket.tmdbId = movie.tmdbId;
		ticket.imdbId = movie.imdbId;
		ticket.title = movie.title;
		ticket.year = movie.releaseDate ? parseInt(movie.releaseDate.slice(0, 4)) : null;
		ticket.user = await User.findOneOrFail(userId);
		ticket.info = info;
		await ticket.save();

		return ticket.id;
	}

	/**
	 * Cancel an active movie request ticket
	 */
	public async cancelMovieTicket() {

	}
}
