const {
    src,
    dest,
    parallel,
    series,
    watch
} = require('gulp');

const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const sass = require('gulp-sass')(require('sass'));
const autoprefixer = require('gulp-autoprefixer');
const cssnano = require('gulp-cssnano');
const concat = require('gulp-concat');
const clean = require('gulp-clean');
//const imagemin = require('gulp-imagemin');
const changed = require('gulp-changed');
const browsersync = require('browser-sync').create();
const webpack = require('webpack'); 
const webpackStream = require('webpack-stream');
const compiler = require('webpack')



function clear() {
    return src('./assets/*', {
            read: false
        })
        .pipe(clean());
}

// JS function 

function js() {
    const source = './lib/*.js';
    return src(source)
    .pipe(webpackStream({
        mode: "production",
        plugins: [
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery'
            }),
        ],
        output: {
            filename: "main.js", 
        },
        module: {
        rules: [
            {
              test: /\.css$/,
              use: ['style-loader', 'css-loader']
            }
        ],
        },
    }, compiler, function(err, stats) {
                
    }
    ))
    .pipe(dest('./assets/js/'));
}

// CSS function 

function css() {
    const source = './sass/**/*.scss';

    return src(source)
        .pipe(changed(source))
        .pipe(sass({
            outputStyle: 'compressed',
            includePaths: ['./node_modules/foundation-sites/scss']}
        ))
        .pipe(autoprefixer({
            overrideBrowserslist: ['last 2 versions', 'ie >= 9', 'android >= 4.4', 'ios >= 7'],
            cascade: false
        }))
        .pipe(rename({
            extname: '.min.css'
        }))
        .pipe(cssnano())
        .pipe(dest('./assets/css/'))
        .pipe(browsersync.stream());
}
function watchFiles() {
    watch('./sass/**/**/*.scss', css);
    watch('./lib/*.js', js);
}

exports.default = series(clear, parallel(js, css));

exports.watch = parallel(watchFiles);