'use strict';
exports.__esModule = true;
var childProcess = require("child_process");
var fs = require("fs");
var os = require("os");
var path = require("path");
var index_1 = require("../subtitle/index");
/**
 * Merges the subtitle and video files into a Matroska Multimedia Container.
 */
function default_1(config, isSubtitled, rtmpInputPath, filePath, streamMode, verbose, done) {
    var subtitlePath = filePath + '.' + (index_1["default"].formats[config.format] ? config.format : 'ass');
    var videoPath = filePath;
    var cp;
    if (streamMode === 'RTMP') {
        videoPath += path.extname(rtmpInputPath);
    }
    else {
        videoPath += '.mp4';
    }
    cp = childProcess.exec(command() + ' ' +
        '-o "' + filePath + '.mkv" ' +
        '"' + videoPath + '" ' +
        (isSubtitled ? '"' + subtitlePath + '"' : ''), {
        maxBuffer: Infinity
    }, function (err) {
        if (err) {
            return done(err);
        }
        unlink(videoPath, subtitlePath, function (errin) {
            if (errin) {
                unlinkTimeout(videoPath, subtitlePath, 5000);
            }
            done(null);
        });
    });
    if (verbose === true) {
        cp.stdin.pipe(process.stdin);
        cp.stdout.pipe(process.stdout);
        cp.stderr.pipe(process.stderr);
    }
}
exports["default"] = default_1;
/**
 * Determines the command for the operating system.
 */
function command() {
    if (os.platform() !== 'win32') {
        return 'mkvmerge';
    }
    return '"' + path.join(__dirname, '../../bin/mkvmerge.exe') + '"';
}
/**
 * Unlinks the video and subtitle.
 * @private
 */
function unlink(videoPath, subtitlePath, done) {
    fs.unlink(videoPath, function (err) {
        if (err) {
            return done(err);
        }
        fs.unlink(subtitlePath, done);
    });
}
/**
 * Attempts to unlink the video and subtitle with a timeout between each try.
 */
function unlinkTimeout(videoPath, subtitlePath, timeout) {
    setTimeout(function () {
        unlink(videoPath, subtitlePath, function (err) {
            if (err) {
                unlinkTimeout(videoPath, subtitlePath, timeout);
            }
        });
    }, timeout);
}
//# sourceMappingURL=merge.js.map