"use strict";

var ConcatSource;
try {
    ConcatSource = require("webpack-core/lib/ConcatSource");
} catch(e) {
    ConcatSource = require("webpack-sources").ConcatSource;
}

function BannerWebpackPlugin(options) {
    this.options = options || {};
    this.chunks = this.options.chunks || {};
}

BannerWebpackPlugin.prototype.apply = function(compiler) {
    compiler.plugin("emit", (compilation, callback) => {
        let allChunks = this.findAsset(compilation);
    //     let chunkKey = Object.keys(this.chunks);
    //     chunkKey.map((chunk, key) => {
    //         let distChunk = this.findAsset(compilation, chunk),
    //             beforeContent = this.chunks[chunk].beforeContent || '',
    //             afterContent = this.chunks[chunk].afterContent || `window.testQQQ = ${global._bili_cache_data}`,
    //             removeBefore = this.chunks[chunk].removeBefore || '',
    //             removeAfter = this.chunks[chunk].removeAfter || '';
    //
        allChunks.forEach(x => {
            let source = compilation.assets[x].source();
            source.replace(new RegExp( '\\);$'), "")
            compilation.assets[x].source = () => {
                return source;
            };

            compilation.assets[x] = new ConcatSource('', compilation.assets[x], `window.__smallAppFE.COVERVIEWDATA = ${JSON.stringify(global._bili_cache_data)};`);
        })
            // let source = compilation.assets[distChunk].source();
    //         source = (removeBefore) ? source.replace(new RegExp('^' + removeBefore), "") : source;
    //         source = (removeAfter) ? source.replace(new RegExp(removeAfter + '$'), "") : source;
    //
    //         compilation.assets[distChunk].source = () => {
    //             return source;
    //         };
    //
    //         compilation.assets[distChunk] = new ConcatSource(beforeContent, compilation.assets[distChunk], afterContent);
    //     });
        callback();
    });

};

BannerWebpackPlugin.prototype.findAsset = function(compilation) {
    // console.log("compilation", compilation)
    let chunks = compilation.chunks;
    let _output = []
    for (let i = 0, len = chunks.length; i < len; i++) {
        _output.push(chunks[i].files[0])
        // if (chunks[i].name === chunk) {
        //     return chunks[i].files[0];
        // }
    }
    return _output;
};

module.exports = BannerWebpackPlugin;
