import type { Cheerio, CheerioAPI, Element } from "cheerio";
import cheerio from "cheerio";
import { ITorrentGalaxyTorrent, Language, LanguageId, Sort, SortOrder} from "./schema";
import { request, convertToBytes } from "../../util";

const BASE_URL = "https://torrentgalaxy.mx/torrents.php?search=";

interface ITorrentGalaxyResults {
	torrents: ITorrentGalaxyTorrent[],
	total_results: number
}

function scrapeRow($: CheerioAPI, row: Cheerio<Element>): ITorrentGalaxyTorrent {
	let children = row.children();
	let category = <string>$(children[0]).find("a").attr("href")?.split("cat=")[1];
	let language = <Language>$(children[2]).find("img[title]").attr("title");
	let name = $(children[3]).text();
	let magnet = <string>$(children[4]).find("a[href^='magnet']").first().attr("href");
	let [size, unit] = $(children[7]).text().split(" ");
	let [seeders, leechers] = $(children[10]).text().slice(1, -1).split('/').map(v => parseInt(v));
	return {
		category: parseInt(category),
		size: convertToBytes(parseFloat(size), unit),
		language, name, magnet, seeders, leechers
	}
}

function scrapeResults(response: string): ITorrentGalaxyResults {
	let torrents: ITorrentGalaxyTorrent[] = [];
	let $ = cheerio.load(response);
	$(".tgxtable .tgxtablerow").each((_, elem) => {
		torrents.push(scrapeRow($, $(elem)));
	});
	return {
		torrents,
		total_results: parseInt($("#filterbox2 > span").text())
	};
}

/**
 * Supports IMDb links too
 */
export async function search(query: string, language: LanguageId = LanguageId.AllLanguages, sort: Sort = Sort.Date, order: SortOrder = SortOrder.Desc) {
	let [status, res] = await request(`${BASE_URL}${encodeURI(query)}&lang=${language}&sort=${sort}&order=${order}`);
	if (status !== 200) {
		throw Error("Non-200 code returned");
	}
	let results = scrapeResults(res);
	return results;
}
