import parseTorrent, { toMagnetURI } from "parse-torrent"
import axios from "axios"
import iconv from "iconv-lite"
import type { AxiosResponse } from "axios"
import type { Readable } from "stream"
import { createWriteStream, readFileSync } from "fs"
import { join } from "path"
import type { CrackGame } from "@/types"

const headers = {
	h1: {
		"content-type": "application/x-www-form-urlencoded charset=UTF-8",
		"x-requested-with": "XMLHttpRequest"
	},
	h2: {
		"accept": "text/html,application/xhtml+xml,application/xmlq=0.9,image/avif,image/webp,image/apng,*/*q=0.8,application/signed-exchangev=b3q=0.7",
		"accept-language": "fr-FR,frq=0.9,en-USq=0.8,enq=0.7",
		"cache-control": "no-cache",
		"pragma": "no-cache",
		"sec-ch-ua": '"Not=A?Brand"v="8", "Chromium"v="110", "Opera GX"v="96"',
		"sec-ch-ua-mobile": "?0",
		"sec-ch-ua-platform": '"Windows"',
		"sec-fetch-dest": "document",
		"sec-fetch-mode": "navigate",
		"sec-fetch-site": "none",
		"sec-fetch-user": "?1",
		"upgrade-insecure-requests": "1",
		"cookie": "online_fix_auth=gAAAAABkKM0s9WNLe_V6euTnJD7UQjppVty9B7OOyHBYOyVcbcejj8F6KveBcLxlf3mlx_vE7JEFPHlrpj-Aq6BFJyKPGzxds_wpcPV2MdXPyDGQLsz4mAvt3qgTgGg25MapWo_fSIOMiAAsF4Gv_uh4kUOiR_jgbHCZWJGPgpNQwU2HFFyvahYR6MzR7nYE9-fCmrev3obkRbro43vIVTTX4UyJMRHadrsY5Q-722TzinCZVmAuJfc= dle_password=89465c26673e0199e5272e4730772c35 _ym_uid=1670534560361937997 _ym_d=1680394955 _ym_isad=2 dle_user_id=2619796 PHPSESSID=3v8sd281sr0n1n9f1p66q25sa2",
		"Referer": "https://online-fix.me/",
		"Referrer-Policy": "strict-origin-when-cross-origin"
	}
}

export async function search(query: string) {
	const body = await fetch("https://online-fix.me/engine/ajax/search.php", { headers: headers.h1, body: `query=${query}`, method: "POST" })
		.then(response => response.arrayBuffer())
		.then(arrayBuffer => { return iconv.decode(Buffer.from(arrayBuffer), "win1251") })
		.catch(console.error)

	try {
		if (!body) return
		const matches = body.split("</div>")[1].split('<span class="seperator fastfullsearch">')[0].split("</a>")
		const games = [] as CrackGame[]
		matches.pop()

		for (const match of matches) {
			const name = match.split('"><span class="searchheading">')[1].split("</span>")[0].slice(0, -8)
			const link = match.split('<a href="')[1].split('"><span class="searchheading">')[0]
			games.push({ name, link })
		}
		return games
	} catch (error) { console.error(error) }
}

export async function repo(game: CrackGame) {
	const body = await fetch(game.link, { headers: headers.h2, body: null, method: "GET" })
		.then(response => response.arrayBuffer())
		.then(arrayBuffer => { return iconv.decode(Buffer.from(arrayBuffer), "win1251") })
		.catch(console.error)

	try {
		if (!body) return
		const name = body.split("https://uploads.online-fix.me:2053/torrents/")[1].split('"')[0]
		const url = `https://uploads.online-fix.me:2053/torrents/${name}`
		return url
	} catch (error) { console.error(error) }
}

export async function torrent(url: string) {
	const response = await fetch(url, { headers: headers.h2, body: null, method: "GET" })
		.catch(console.error)

	try {
		if (!response) return
		const body = await response.text()
		const file = body.split('<a href="')[2].split('">')[0]
		return file
	} catch (error) { console.error(error) }
}

export async function download(url: string, file: string) {
	const filePath = join(__dirname, "@/public/cracks/", file)
	const writer = createWriteStream(filePath)
	try {
		await axios({ url: url + file, method: "GET", responseType: "stream", headers: headers.h2 })
			.then((response: AxiosResponse<Readable>) => {
				return new Promise((resolve, reject) => {
					response.data.pipe(writer)
					writer.on("error", err => { writer.close(); reject(err) })
					writer.on("close", () => { resolve(true) })
				})
			})
			.catch(console.error)
		return filePath
	} catch (error) { console.error(error) }
}

export function magnet(filePath: string) {
	const torrentData = parseTorrent(readFileSync(filePath))
	const uri = toMagnetURI(torrentData)
	return uri
}
