// Include gulp
var $ = require('gulp-load-plugins')();
var gulp = require('gulp');
var sequence = require('run-sequence');

// Postcss plugins
var autoprefixer = require('autoprefixer');
var base64 = require('postcss-base64');

/**
 * File paths to various assets are defined here.
 */
var PATHS = {
    sass: [
        'assets/scss/*.scss',
        'assets/scss/**/*.scss'
    ]
};

// Compile min CSS
gulp.task('build:styles', function () {
    return gulp.src('assets/scss/main.scss')
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            includePaths: PATHS.sass,
            outputStyle: 'compressed'
        })
            .on('error', $.sass.logError))
        .pipe($.postcss([
            autoprefixer(),
            base64({
                pattern: /<svg.*<\/svg>/i,
                prepend: 'data:image/svg+xml;base64,'
            })
        ]))
        .pipe($.rename({
            basename: "theme",
            suffix: '.min'
        }))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('build/css'))
});

// Compile uncompressed CSS
gulp.task('dev:styles', function () {
    return gulp.src('assets/scss/main.scss')
        .pipe($.sass({
            includePaths: PATHS.sass,
            outputStyle: 'expanded',
            indentType: 'tab',
            indentWidth: 1
        })
            .on('error', $.sass.logError))
        .pipe($.postcss([
            autoprefixer(),
            base64({
                pattern: /<svg.*<\/svg>/i,
                prepend: 'data:image/svg+xml;base64,'
            })
        ]))
        .pipe($.rename({
            basename: "theme",
            suffix: '.min'
        }))
        .pipe(gulp.dest('build/css'))
});

// Watch tasks
gulp.task('watch', function () {
    // Watch .scss files
    gulp.watch(PATHS.sass, ['build:styles']);
});

// DEV Watch tasks
gulp.task('watch:dev', function () {
    // Watch .scss files
    gulp.watch(PATHS.sass, ['dev:styles']);
});

// Build and minify the theme assets
gulp.task('build', function (done) {
    sequence([
        'build:styles'
    ], done);
});

// Build the theme assets un-minified
gulp.task('dev', function (done) {
    sequence([
        'dev:styles'
    ], done);
});

// Default task, run the build
gulp.task('default', ['build']);
