"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTorrentsRouter = void 0;
const common_stuff_1 = require("common-stuff");
const helpers_1 = require("../helpers");
const openapi_1 = require("../helpers/openapi");
const torrentToJson = (v, domain, encodeToken) => {
    return {
        name: v.name,
        infoHash: v.infoHash,
        downloadSpeed: v.getDownloadSpeed(),
        downloaded: v.getDownloaded(),
        link: v.link,
        started: v.created.getTime(),
        updated: v.updated.getTime(),
        files: v.files.map((f) => ({
            name: f.name,
            path: f.path,
            type: f.type,
            length: f.length,
            stream: `${domain}${helpers_1.getSteamUrl(v.link, f.path, encodeToken)}`,
        })),
        playlist: `${domain}${helpers_1.getPlaylistUrl(v.link, encodeToken)}`,
    };
};
function getTorrentsRouter({ config }, client) {
    const encodeToken = config.security.streamApi.key || config.security.apiKey;
    return [
        openapi_1.createRoute('createTorrent', async (req, res) => {
            const { torrent: link } = req.query;
            const domain = req.protocol + '://' + req.get('host');
            const torrent = await client.addTorrent(link);
            return res.json(torrentToJson(torrent, domain, encodeToken));
        }),
        openapi_1.createRoute('getTorrents', (req, res) => {
            const domain = req.protocol + '://' + req.get('host');
            return res.json(client.getTorrents().map((v) => torrentToJson(v, domain, encodeToken)));
        }),
        openapi_1.createRoute('getTorrent', (req, res) => {
            const { infoHash } = req.params;
            const domain = req.protocol + '://' + req.get('host');
            const torrent = client.getTorrent(infoHash);
            if (torrent) {
                return res.json(torrentToJson(torrent, domain, encodeToken));
            }
            throw new common_stuff_1.HttpError(common_stuff_1.HttpStatusCodes.NOT_FOUND);
        }),
    ];
}
exports.getTorrentsRouter = getTorrentsRouter;
