import { IMovieSearchInfo } from "@autoplex-api/torrent-search/dist/typings";
import { ITorrentMetaInfo, parseMovieTorrentName } from "./parsing";

export default class Torrent
{
	/**
	 * The provider of the torrent
	 */
	public readonly provider: string;

	/**
	 * The name of the torrent
	 */
	public readonly name: string;

	/**
	 * The size of the torrent in bytes (if available)
	 */
	public readonly size: number | null;

	/**
	 * The number of seeders (if available)
	 */
	public readonly seeders: number;

	/**
	 * Download link (if available)
	 */
	protected readonly link: string | null;

	/**
	 * Metadata of the torrent
	 */
	public readonly metadata: ITorrentMetaInfo;

	/**
	 * Create a new Torrent instance
	 *
	 * @param name    The name of the torrent
	 * @param size    The size of the torrent in bytes (if available)
	 * @param seeders The number of seeders (if available)
	 * @param link    The link to the torrent (if available)
	 */
	public constructor(provider: string, movie: IMovieSearchInfo, name: string, size?: number, seeders?: number, link?: string) {
		this.provider = provider;
		this.name     = name.trim();
		this.size     = size ?? null;
		this.seeders  = seeders ?? 1;
		this.link     = link ?? null;
		this.metadata = parseMovieTorrentName(name, movie);
	}

	/**
	 * Return a link to download (magnet or .torrent)
	 */
	public async downloadLink() {
		if (this.link === null) {
			throw Error("Magnet link does not exist");
		}
		return this.link;
	}

	/**
	 * Get the info hash of the torrent if it exists
	 */
	public infoHash() {
		if (this.link === null) {
			return null;
		}
		let infoHash = (this.link.match(/(?<=^magnet:\?xt=urn:btih:)[0-9a-f]+/gi) ?? [])[0];
		return infoHash ?? null;
	}

	/**
	 * Serialize this torrent into a string
	 */
	public toString() {
		return `Name: ${this.name}; Size: ${this.size}; Seeders: ${this.seeders};`
	}
}
