import { Resolution } from "./parsing";
import Torrent from "./Torrent";

/**
 * Rank a list of torrents from best to worst to download
 */
export function rankTorrents(torrents: Torrent[]) {
	torrents.sort(sortCompare);
	let preferred = torrents.filter(selectPreferredTorrents);
	return preferred;
}

/**
 * Filter out unwanted torrents
 */
function selectPreferredTorrents(torrent: Torrent) {
	if (torrent.seeders == 0 || torrent.metadata.containsOtherLanguage) {
		return false;
	}
	if (torrent.metadata.resolution == Resolution.HD4k) {
		return torrent.size != null && torrent.size < 10*1024*1024*1024; // 10GB
	}
	return true;
}

/**
 * A comparator for ranking torrents
 *
 * @param a Left side
 * @param b Right side
 */
function sortCompare(a: Torrent, b: Torrent) {
	// Languages
	let languageCmp = <any>a.metadata.containsOtherLanguage - <any>b.metadata.containsOtherLanguage;
	if (languageCmp !== 0) {
		return languageCmp;
	}
	// Resolution
	let resolutionCmp = a.metadata.resolution - b.metadata.resolution;
	if (resolutionCmp !== 0) {
		return resolutionCmp;
	}

	// If one has only a few seeds, don't worry about the other info. Prioritize seed count
	if (a.seeders < 5 || b.seeders < 5) {
		let seedersCmp = b.seeders - a.seeders;
		if (seedersCmp != 0) {
			return seedersCmp;
		}
	}

	// Sort by the file size
	let fileSizeCmp = (a.size ?? 0) - (b.size ?? 0);
	if (fileSizeCmp !== 0) {
		return fileSizeCmp;
	}
	return 0;
}
