import CssModulesBuildPlugin from './css-modules-build-plugin';
import pluginOptionsWrapper from './options';

const pluginOptions = pluginOptionsWrapper.options;

ImportPathHelpers.init(Plugin);

if (pluginOptions.extensions.indexOf('css') === -1)
	registerCompiler();
else
	monkeyPatchToHandleCssExtension();


function registerCompiler() {
	Plugin.registerCompiler({
		extensions: pluginOptions.extensions,
		archMatching: pluginOptions.specificArchitecture,
		filenames: pluginOptions.filenames
	}, function () {
		return new CssModulesBuildPlugin(Plugin);
	});
}

/**
 * Monkey patch _registerSourceProcessor and SourceProcessorSet.merge so we can block the default CSS compiler
 */
function monkeyPatchToHandleCssExtension() {
	const registerSourceProcessor = Plugin._registerSourceProcessor;
	Plugin._registerSourceProcessor = function (options, factory, {sourceProcessorSet, methodName, featurePackage}) {
		const buildPluginMerge = sourceProcessorSet.constructor.prototype.merge;
		sourceProcessorSet.constructor.prototype.merge = function (otherSet, options) {
			/**
			 * If a css plugin handler has already been added,
			 * don't merge the meteor package, which only includes the 'css' package
			 */
			if (otherSet._myPackageDisplayName !== 'meteor' || !('css' in this._byExtension)) {
				buildPluginMerge.call(this, ...arguments);
				return;
			}
		};
		registerSourceProcessor(options, factory, {sourceProcessorSet, methodName, featurePackage});
	};

	registerCompiler();

	Plugin._registerSourceProcessor = registerSourceProcessor;
}

@@ -1295,16 +1295,720 @@
 ion)) %7B%0A
+%09%09%09%09/* If we're using CSS modules inside of a package, it's possible that Meteor's CSS build plugin got merged%0A%09%09%09%09 * before we could block it. In that case, unregister the Meteor CSS processor.%0A%09%09%09%09 */%0A%09%09%09%09if (('css' in this._byExtension) && 'css' in otherSet._byExtension) %7B// && sp.isopack.displayName() === 'meteor')%0A%09%09%09%09%09const previouslyRegisteredSourceProcessor = this._byExtension.css%5B0%5D;%0A%09%09%09%09%09if (previouslyRegisteredSourceProcessor.isopack.displayName() === 'meteor' && otherSet._myPackageDisplayName === 'nathantreid:css-modules') %7B%0A%09%09%09%09%09%09this.allSourceProcessors.splice(this.allSourceProcessors.indexOf(previouslyRegisteredSourceProcessor), 1)%0A%09%09%09%09%09%09delete this._byExtension.css;%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A
 %09%09%09%09buil

fix processing of .css extension in packages (address conflict in #41)