import { Entity, PrimaryGeneratedColumn, Column, BaseEntity, ManyToOne, OneToMany, OneToOne, JoinColumn, CreateDateColumn, Not, IsNull } from "typeorm";
import { MovieInfo } from "./MovieInfo";
import { MovieTorrent } from "./MovieTorrent";
import { User } from "./User";

@Entity()
export class MovieTicket extends BaseEntity
{
	@PrimaryGeneratedColumn()
	id!: number;

	@Column({ type: "int" })
	tmdbId!: number;

	@Column({ type: "varchar", length: 27, nullable: true })
	imdbId!: string | null;

	@Column({ type: "varchar" })
	title!: string;

	@Column({ type: "year", nullable: true })
	year!: number | null;

	@CreateDateColumn()
	createdAt!: Date;

	@Column({ default: false })
	isFulfilled!: boolean;

	@Column({ default: false })
	isCanceled!: boolean;

	@Column({ default: false })
	isStale!: boolean;

	@ManyToOne(() => User, user => user.movieTickets)
	user!: User;

	@OneToMany(() => MovieTorrent, torrent => torrent.movieTicket)
	torrents!: MovieTorrent[];

	@OneToOne(() => MovieInfo, { nullable: true })
	@JoinColumn()
	info!: MovieInfo | null;

	/**
	 * Fulfill the current ticket instance
	 */
	async fulfill() {
		this.isFulfilled = true;
		return await this.save();
	}

	/**
	 * @TODO This needs to check for fulfilled tickets too, but not there yet
	 * Fetch all active ticket ID's
	 */
	public static async activeTicketMap() {
		let tickets = await MovieTicket.find({ where: { tmdbId: Not(IsNull()), isCanceled: false } });
		let result: {[tmdbId: number]: number} = {};
		for (let ticket of tickets) {
			result[<number>ticket.tmdbId] = ticket.id;
		}
		return result;
	}

	/**
	 * Insert a request via IMDb movie details
	 */
	public static async requestImdb(user: User, imdbId: string, title: string, year: number) {
		let ticket = new MovieTicket();
		ticket.imdbId = imdbId;
		ticket.title = title;
		ticket.year = year;
		ticket.user = user;
		return await ticket.save();
	}

	/**
	 * Insert a rquest via TMDb movie details
	 */
	// public static async requestTmdb(user: User, movie: IApiMovieDetails) {
	// 	let info = new MovieInfo();
	// 	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 = user;
	// 	ticket.info = info;
	// 	return await ticket.save();
	// }
}
