/**
 * Sass compilation and Autoprefixer
 */
module.exports = function(gulp, projectPath, themePath, includesPath, config) {
    var TASK_NAME = 'sass',
        DEFAULT_CONFIG = {
            'src': ['**/*.scss', '!**/.tmp/**/*.scss', '!**/assets/**/*.scss'],
            'sourceMaps': true,
            'cssNano': false,
            'dest': '/',
            'sassOptions': {
                errLogToConsole: true,
                outputStyle: 'expanded',
                includePaths: [projectPath + includesPath]
            },
            'autoprefixerOptions': {}
        };

    return {
        name: TASK_NAME,
        task: function getSassTask(done) {
            var _subTasks = [],
                _config,
                _extend = require('merge'),
                sass = require('gulp-sass'),
                postcssPlugins = [],
                sourcemaps = require('gulp-sourcemaps'),
                gulpif = require('gulp-if'),
                postcss = require('gulp-postcss'),
                autoprefixer = require('autoprefixer'),
                cssnano = require('cssnano'),
                merge = require('merge-stream');

            _config = _extend.recursive(true, DEFAULT_CONFIG, config);

            if (_config.cssNano === false) {
                postcssPlugins = [autoprefixer(_config.autoprefixerOptions)]
            } else {
                postcssPlugins = [autoprefixer(_config.autoprefixerOptions), cssnano()]
            }

            _subTasks.push(
                gulp.src(
                    _config.src.map(function (item) {
                        if (item.indexOf('!') === -1) {
                            return themePath + item;
                        }
                        return item;
                    }),
                    {
                        cwd: projectPath
                    })
                    .pipe(gulpif(_config.sourceMaps === true, sourcemaps.init()))
                    .pipe(sass(_config.sassOptions).on('error', sass.logError))
                    .pipe(postcss(postcssPlugins))
                    .pipe(gulpif(_config.sourceMaps === true, sourcemaps.write()))
                    .pipe(gulp.dest(
                        function (file) {
                            return file.base;
                        }
                    ))
            );

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

