"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterFiles = exports.downloadTrackers = exports.mirrors = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
const path_1 = require("path");
exports.mirrors = [
    'https://ngosang.github.io/trackerslist/trackers_all.txt',
    'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all.txt',
    'https://cdn.jsdelivr.net/gh/ngosang/trackerslist/trackers_all.txt',
];
/**
 * Download tracker list from https://github.com/ngosang/trackerslist
 */
async function downloadTrackers() {
    for (const mirror of exports.mirrors) {
        try {
            return node_fetch_1.default(mirror, {
                timeout: 3000,
            })
                .then((v) => v.text())
                .then((v) => v
                .split('\n')
                .map((v) => v.trim())
                .filter((v) => !!v));
        }
        catch {
            continue;
        }
    }
    throw new Error('Failed to download trackers');
}
exports.downloadTrackers = downloadTrackers;
/**
 * Find a file by given options, returns the biggest file
 * @param files
 * @param options
 */
function filterFiles(files, options) {
    const filteredFiles = files.filter((f, i) => (options.fileIndex === undefined || options.fileIndex == i + 1) &&
        (options.file === undefined ||
            [f.name, f.path.replace(/^\//, '')]
                .map((v) => v.toLowerCase())
                .includes(options.file.replace(/^\//, '').toLowerCase())) &&
        (options.fileType === undefined ||
            [...f.type.split('/'), f.type, path_1.extname(f.name)]
                .map((v) => v.toLowerCase().replace('.', ''))
                .includes(options.fileType.toLowerCase().replace('.', ''))));
    const file = filteredFiles.find((f) => options.file && f.path === options.file);
    return file ? [file] : [...filteredFiles].sort((a, b) => b.length - a.length);
}
exports.filterFiles = filterFiles;
