const fs = require('fs');
const path = require('path');
const stream = require('stream');
const Transform = stream.Transform;
const Readable = stream.Readable;
const MultiStream = require('multistream');

// combine all given files into one with a multi stream (this is done asynchronously)
// line endings are added after each file and sourcemap urls are removed
function concatFiles(inputPathArray, outputPath) {
    const write = fs.createWriteStream(outputPath, {flags: 'w'});
    const removeSourcemap = new Transform({
        transform(chunk, encoding, callback) {
            const result = chunk.toString().replace(/(sourceMappingURL=(?:\S)+)/, '(removed source map)');
            this.push(result);
            callback();
        }
    });
    new MultiStream(inputPathArray.reduce(function(prev, curr) {
        const endline = new Readable();
        endline.push('\n\n');
        endline.push(null);
        return prev.concat(
            fs.createReadStream(curr),
            endline
        );
    }, []))
        .pipe(removeSourcemap)
        .pipe(write);
}

function copyFile(inputPath, outputPath, callback) {
    const read = fs.createReadStream(inputPath);
    const write = fs.createWriteStream(outputPath);
    read.pipe(write);
    if (callback) {
        write.on('finish', callback);
    }
}

// copy all files to the given directory
// will create directory if missing
function copyFiles(inputPathArray, outputDirPath) {
    if (!fs.existsSync(outputDirPath)) {
        fs.mkdirSync(outputDirPath);
    }
    inputPathArray.forEach(function(filePath) {
        const filename = path.basename(filePath);
        copyFile(filePath, path.resolve(outputDirPath, filename));
    });
}

module.exports = {
    concatFiles,
    copyFiles,
    copyFile
};
