const through = require('through2');
const Vinyl = require('vinyl');

module.exports = function(origins)
{
    // combines (concatenates) processed css/js assets from multiple origin folders into a single folder

    //  e.g.
    //
    //  when origins == [ "base", "info" ]
    //  and
    //  when the incoming processed assets are:
    //  base/assets/stylesheets/application.css
    //  base/assets/stylesheets/controllers/home_page.css
    //  base/assets/stylesheets/controllers/text_page.css
    //  info/assets/stylesheets/application.css
    //  info/assets/stylesheets/controllers/home_page.css
    //  info/assets/stylesheets/controllers/other_page.css
    //
    //  then the result is:
    //  stylesheets/application.css             <-- contains concatenated application.css from base and info
    //  stylesheets/controllers/home_page.css   <-- contains concatenated controllers/home_page.css from base and info
    //  stylesheets/controllers/text_page.css   <-- contains only controllers/text_page.css from base
    //  stylesheets/controllers/other_page.css  <-- contains only controllers/other_page.css from info

    var basePath;
    var assetCollection = {};

    function collectFiles(file, encoding, callback)
    {
        const pathPattern = new RegExp("^(" + origins.join("|") + ")\/assets\/(.+)$");
        const pathParts = file.relative.match(pathPattern);
        if (!pathParts)
        {
            throw new Error('originCombiner: unrecognized asset path: "' + file.relative + '"');
        }

        if (!basePath)
        {
            basePath = file.base;
        }

        const assetType = pathParts[1];
        const assetPath = pathParts[2];

        if (!assetCollection[assetPath])
        {
            assetCollection[assetPath] = {}
            origins.forEach(function(origin)
            {
                assetCollection[assetPath][origin] = null;
            });
        }

        assetCollection[assetPath][assetType] = file;

        callback();
    }


    function endStream(callback)
    {
        var stream = this;
        Object.keys(assetCollection).forEach(function(key, index)
        {
            const asset = assetCollection[key];
            const combinedAbsolutePath = basePath + key;

            var contentStrings = [];

            origins.forEach(function(origin)
            {
                if (asset[origin])
                {
                    contentStrings.push( asset[origin].contents.toString() );
                }
            });

            const file = new Vinyl(
            {
                base: basePath,
                path: combinedAbsolutePath,
                contents: new Buffer(contentStrings.join("\n"))
            });

            stream.push(file);
        });

        callback();
    }

    return through.obj(collectFiles, endStream);
};
