"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const Direct = require("../features/boombox/Direct");
const encoder_1 = require("../features/boombox/encoder");
const storyboard_1 = require("storyboard");
const compactd_models_1 = require("compactd-models");
const database_1 = require("../database");
const mime = require("mime");
encoder_1.default.INSTANCE.on('error', (err) => {
    console.log(err);
});
encoder_1.default.INSTANCE.on('start', function (commandLine) {
    console.log('Spawned Ffmpeg with command: ' + commandLine);
});
const audioType = require('audio-type');
function default_1(app) {
    app.post('/api/boombox/direct', (req, res) => {
        Direct.createSession(req.body.track).then((token) => {
            res.status(201).send({ ok: true, token });
        }).catch((err) => {
            storyboard_1.mainStory.error('boombox', err.message, { attach: err });
            res.status(err.status || 500).send({ ok: false, error: 'Couldnt create token' });
        });
    });
    app.get('/api/boombox/:artist/:album/:number/:track/:preset', (req, res) => __awaiter(this, void 0, void 0, function* () {
        const { artist, album, number, track, preset } = req.params;
        const id = compactd_models_1.trackURI({ artist, album, number, name: track });
        if (!encoder_1.ENCODER_PRESETS[preset]) {
            return res.status(404).send({
                error: 'preset not found'
            });
        }
        const files = new database_1.default('files');
        const docs = yield files.allDocs({
            include_docs: true,
            startkey: id,
            endkey: id + '\uffff'
        });
        const file = docs.rows[0].doc;
        encoder_1.default.INSTANCE.setEncoderOptions(encoder_1.ENCODER_PRESETS[preset]);
        const buffer = yield encoder_1.default.INSTANCE.run(file.path);
        let type = mime.getType(audioType(buffer));
        // Owrkaround
        if (type === 'audio/x-flac') {
            type = 'audio/flac';
        }
        res.setHeader('content-type', type);
        res.setHeader('transfer-encoding', 'chunked');
        res.setHeader('connection', 'chunked');
        res.setHeader('accept-ranges', 'bytes');
        res.setHeader('transfer-encoding', 'chunked');
        const size = buffer.byteLength;
        if (req.headers['range']) {
            const [b, range] = req.headers['range'].split('=');
            if (b === 'bytes') {
                let [start, end] = range.split('-').map(i => +i);
                if (!end || end < start)
                    end = size - 1;
                const opts = {
                    start: start - 0,
                    end: end - 0
                };
                res.status(206);
                res.setHeader('Content-Range', `bytes ${start}-${end}/${size}`);
                res.setHeader('Content-Length', end - start + 1);
                res.send(buffer.slice(start, end));
                return;
            }
        }
        res.send(buffer);
    }));
}
exports.default = default_1;
function player(app) {
    app.get('/api/boombox/stream/:token', (req, res) => {
        res.sendFile(Direct.readToken(req.params.token), {
            maxAge: '1d'
        });
    });
}
exports.player = player;
//# sourceMappingURL=boombox.js.map