const merge = require('lodash/merge');
const gulp = require('gulp');
const sass = require('gulp-sass');
const gulpif = require('gulp-if');
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');

/*
 *  Default configuration for this task. Adjustments specific
 *  to the site package should be specified as overrrides in its
 *  gulpfile.
 */
const defaultConfig = {
    /*
     *  Path glob for all stylesheet entry files in this
     *  project. Supports defining one or many stylesheets.
     *  Should be relative to the project root.
     */
    src: './Sass/*.scss',

    /*
     *  Path where the output bundle(s) will be placed.
     *  Should be relative to the target site package.
     *  Should NOT begin with a leading slash.
     */
    dist: './Packages/Sites/Newland.CityTheme/Resources/Public/Stylesheets',

    /*
     *  Options to be passed on to sass pre-processor.
     *  See https://github.com/sass/node-sass#usage for
     *  available settings.
     */
    sassOptions: {
        includePaths: '../node_modules',
    },
};

module.exports = config => {
    // Merge default and project-specific configuration.
    const mergedConfig = config ? merge(defaultConfig, config) : defaultConfig;

    // Check process execution environment.
    const isDevelopment = process.env.NODE_ENV && process.env.NODE_ENV == 'development';

    return gulp
        .src(mergedConfig.src)

        // Start sourcemap generation while in dev mode.
        .pipe(gulpif(isDevelopment, sourcemaps.init()))

        // Run sass preprocessing
        .pipe(sass(mergedConfig.sassOptions).on('error', sass.logError))

        /*
         *   Post-processing with Postcss.
         *   Configuration/plugins can be adjusted in postcss.config.js.
         */
        .pipe(postcss().on('error', function (error) {
            // If you want details of the error in the console
            // eslint-disable-next-line no-console
            console.log(error.toString());
            this.emit('end');
        }))

        // Write sourcemap files if in dev mode
        .pipe(gulpif(isDevelopment, sourcemaps.write('.')))

        // Output processed CSS file
        .pipe(gulp.dest(mergedConfig.dist));
};
