'use strict';

var gulp = require('gulp');
var gulpif = require('gulp-if');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var autoprefixer = require('gulp-autoprefixer');
var jsmin = require('gulp-jsmin');
var stripDebug = require('gulp-strip-debug');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
// var mainBowerFiles = require('main-bower-files');
var svgmin = require('gulp-svgmin');

// to get minified assets run `gulp --env=prod`
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
var prod = argv.env == 'prod' ? true : false;

function handleError(err) {
  console.log(err.toString());
}

gulp.task('scripts', gulp.series(function (done) {
  gulp.src(['./assets/scripts/main.js'])
    // .pipe(concat('main.js'))
    .pipe(gulpif(prod, stripDebug()))
    .pipe(gulpif(prod, jsmin()))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./assets/dist/scripts/'));
  done();
}));

gulp.task('styles', gulp.series(function (done) {
  gulp.src(['./assets/styles/app.scss'])
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
        browsers: ['last 2 versions'],
        cascade: false
    })).on('error', handleError)
    // .pipe(prod ? cssmin() : util.noop())
    .pipe(gulpif(prod, cssmin()))
    // .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./assets/dist/styles/'));
    done();
}));

// gulp.task('bower', function() {
//     gulp.src(mainBowerFiles({
//       "overrides":{
//         "masonry-layout":{
//           "main":"./dist/masonry.pkgd.min.js"
//         },
//         "imagesloaded":{
//           "main":"./imagesloaded.pkgd.min.js"
//         },
//         "jquery":{"ignore":true},
//         "ev-emitter":{"ignore":true},
//         "fizzy-ui-utils":{"ignore":true},
//         "get-size":{"ignore":true},
//         "outlayer":{"ignore":true},
//       }
//     }))
//       .pipe(gulp.dest('./assets/dist/bower/'));
// });

gulp.task('svg', gulp.series(function (done) {
  gulp.src(['./assets/img/*.svg'])
    .pipe(svgmin())
    .pipe(gulp.dest('./assets/dist/img'));
  done();
}));

// default gulp task
 //'bower',
gulp.task('default', gulp.series(['scripts', 'styles', 'svg'], function(done) {
  gulp.watch('./assets/styles/*.scss', gulp.series('styles'));
  gulp.watch('./assets/styles/base/*.scss', gulp.series('styles'));
  gulp.watch('./assets/scripts/*.js', gulp.series('scripts'));
  gulp.watch('./assets/img/*.svg', gulp.series('svg'));
  done();
}));
