import loadPlugins from './plugins-loader';


CssModulesBuildPlugin = class CssModulesBuildPlugin {
	processFilesForTarget(files) {
		var processor = new CssModulesProcessor('./', loadPlugins());
		processFiles(files, processor);
	}
};


function processFiles(files, processor) {
	const allFiles = createAllFilesMap(files);
	files.forEach(processFile.bind(this));

	function processFile(file) {
		var source = {
			path: ImportPathHelpers.getImportPathInPackage(file),
			contents: file.getContentsAsBuffer().toString('utf8')
		};
		return processor.process(source, './', allFiles)
			.then((result)=> {
				file.addStylesheet({
					data: result.source,
					path: file.getPathInPackage().replace('\.mss$', '.css'),
					sourceMap: JSON.stringify(result.sourceMap)
				});

				file.addJavaScript({
					data: Babel.compile('' +
						`var styles = ${JSON.stringify(result.tokens)};\n` +
						'export { styles as default, styles };').code,
					path: file.getPathInPackage() + '.js'
				});
			}).await();
	}
}

function createAllFilesMap(files) {
	var allFiles = new Map();
	files.forEach((inputFile) => {
		const importPath = ImportPathHelpers.getImportPathInPackage(inputFile);
		allFiles.set(importPath, inputFile);
	});
	return allFiles;
}

@@ -597,16 +597,40 @@
 lt)=%3E %7B%0A
+%09%09%09%09if (result.source)%0A%09
 %09%09%09%09file
@@ -642,24 +642,25 @@
 tylesheet(%7B%0A
+%09
 %09%09%09%09%09data: r
@@ -673,16 +673,17 @@
 source,%0A
+%09
 %09%09%09%09%09pat
@@ -741,16 +741,17 @@
 ),%0A%09%09%09%09%09
+%09
 sourceMa
@@ -794,13 +794,38 @@
 %09%09%09%09
+%09
 %7D);%0A%0A
+%09%09%09%09if (result.tokens)%0A%09
 %09%09%09%09
@@ -841,24 +841,25 @@
 avaScript(%7B%0A
+%09
 %09%09%09%09%09data: B
@@ -876,16 +876,17 @@
 le('' +%0A
+%09
 %09%09%09%09%09%09%60v
@@ -942,16 +942,17 @@
 +%0A%09%09%09%09%09%09
+%09
 'export 
@@ -991,24 +991,25 @@
 .code,%0A%09%09%09%09%09
+%09
 path: file.g
@@ -1034,16 +1034,17 @@
 + '.js'%0A
+%09
 %09%09%09%09%7D);%0A

fix #11 - MSS files that are empty after processing will not be included