/**
 * Minify/Compress images for theme based on settings passed
 */
module.exports = function(gulp, projectPath, themePath, config) {
    var TASK_NAME = 'imagemin',
        DEFAULT_CONFIG = {
            'src': ['**/*.{png,gif,jpg,svg}', '!**/.tmp/**/*', '!**/assets/**/*'],
            'dest': '/',
            'gifsicle': {
                'interlaced': true
            },
            'mozjpeg': {
                'progressive': true
            },
            'optipng': {
                'optimizationLevel': 5
            },
            'svgo': {
                'plugins': [
                    {
                        'cleanupIDs': true
                    }
                ]
            }
        };

    return {
        name: TASK_NAME,
        task: function getImageminTask(done) {
            var _subTasks = [],
                _config,
                _extend = require('merge'),
                imagemin = require('gulp-imagemin'),
                newer = require('gulp-newer'),
                merge = require('merge-stream');

            _config = _extend.recursive(true, DEFAULT_CONFIG, config);
            console.log('Path:' + (projectPath + themePath));
            _subTasks.push(
                gulp.src(
                    _config.src.map(function (item) {
                        if (item.indexOf('!') === -1) {
                            return themePath + item;
                        }
                        return item;
                    }),
                    {
                        cwd: projectPath,
                        allowEmpty: true
                    })
                .pipe( newer(projectPath + themePath + _config.dest) )
                .pipe( imagemin([
                    imagemin.gifsicle(config.gifsicle),
                    imagemin.mozjpeg(config.mozjpeg),
                    imagemin.optipng(config.optipng),
                    imagemin.svgo(config.svgo)
                ], {verbose: true}) )
                .pipe(gulp.dest(
                    projectPath + themePath + _config.dest
                ))
            );

            return merge(_subTasks);
        },
        setProjectPath: function (path) {
            projectPath = path;
        },
        setThemePath: function (path) {
            themePath = path;
        }
    }
};

