import postcss from 'postcss';
import _ from 'lodash';
import {
	defaults,
	prepareFilterBy,
	prepareGroupBy,
	extractImages,
	applyFilterBy,
	applyGroupBy,
	setTokens,
	runSpritesmith,
	saveSpritesheets,
	mapSpritesheetProps,
	updateReferences
} from './core';

/**
 * Plugin registration.
 */
export default postcss.plugin('postcss-sprites', (opts = {}) => {
	return (css, result) => {
		// Extend defaults
		opts = _.merge({}, defaults, opts);

		// Prepare filter & group functions
		prepareFilterBy(opts, result);
		prepareGroupBy(opts);

		// Process it
		return extractImages(css, opts, result)
			.spread((opts, images) => applyFilterBy(opts, images))
			.spread((opts, images) => applyGroupBy(opts, images))
			.spread((opts, images) => setTokens(css, opts, images))
			.spread((root, opts, images) => runSpritesmith(opts, images))
			.spread((opts, images, spritesheets) => saveSpritesheets(opts, images, spritesheets))
			.spread((opts, images, spritesheets) => mapSpritesheetProps(opts, images, spritesheets))
			.spread((opts, images, spritesheets) => updateReferences(css, opts, images, spritesheets))
			.spread((root, opts, images, spritesheets) => {
				result.warn(`${spritesheets.length} ${spritesheets.length > 1 ? 'spritesheets' : 'spritesheet'} generated.`);
			})
			.catch((err) => {
				console.error(`postcss-sprites: An error occurred while processing files - ${err.message}`);
				console.error(err.stack);
				throw err;
			});
	}
});

@@ -341,16 +341,19 @@
 s', (opt
+ion
 s = %7B%7D) 
@@ -407,16 +407,22 @@
 aults%0A%09%09
+const 
 opts = _
@@ -445,16 +445,19 @@
 lts, opt
+ion
 s);%0A%0A%09%09/

Fix options merging