"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _path = require("path");

var _path2 = _interopRequireDefault(_path);

var _rtlcss = require("rtlcss");

var _rtlcss2 = _interopRequireDefault(_rtlcss);

var _webpackSources = require("webpack-sources");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const pluginName = "rtl-css-transform-webpack-plugin";
const isCss = filename => _path2.default.extname(filename) === ".css";
class RtlCssPlugin {
    constructor(options) {
        this.options = {
            filename: "[name].rtl.css",
            sourcemap: undefined,
            config: undefined
        };
        if (typeof options === "object") {
            if (typeof options.filename === "string") {
                this.options.filename = options.filename;
            }
            if (typeof options.sourcemap === "boolean") {
                this.options.sourcemap = options.sourcemap;
            }
            if (typeof options.config === "object") {
                this.options.config = options.config;
            }
        }
    }
    apply(compiler) {
        const { filename, sourcemap, config } = this.options;
        const { devtool } = compiler.options;
        const postcssOptions = {
            map: sourcemap === undefined && !!devtool || !!sourcemap
        };
        compiler.hooks.compilation.tap(pluginName, compilation => {
            compilation.hooks.optimizeChunkAssets.tapAsync(pluginName, (chunks, callback) => {
                chunks.forEach(chunk => {
                    chunk.files.filter(isCss).forEach(chunkFilename => {
                        const asset = compilation.assets[chunkFilename];
                        const result = _rtlcss2.default.configure(config).process(asset.source(), postcssOptions);
                        const rawSource = new _webpackSources.RawSource(result.css);
                        const assetFilename = compilation.getPath(filename, {
                            chunk
                        });
                        compilation.assets[assetFilename] = rawSource;
                    });
                });
                callback();
            });
        });
    }
}
exports.default = RtlCssPlugin;