var gulp = require('gulp');
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var modernizr = require('gulp-modernizr');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');

var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var to5ify = require('6to5ify');

var bs = require('browser-sync').create();
// //----------------------------------------------- Configs
var paths = {
  sass: {
    src: './dev-assets/styles/**/*.{scss,sass}',
    main: './dev-assets/styles/main.scss',
    dest: './css'
  }
};

// ---------------------------------------------- Browser init

gulp.task('init-live-reload', function() {
    bs.init({
        // server: { baseDir: './'},
        // proxy: "localhost/",
        // browser: 'firefox'
    })
});

// ---------------------------------------------- Gulp Tasks
gulp.task('styles', function(done){
  return gulp.src([
    paths.sass.main
  ])
  .pipe(sass(
    {includePaths: ['./node_modules/foundation-sites/scss']}
  ))
  .pipe(concat('app.css'))
  .pipe(gulp.dest(paths.sass.dest))
  .pipe(bs.stream());

  done();
});

//browserify

gulp.task('scripts', function(done){

  // browserify('./dev-assets/main.js')
  //   .transform(to5ify)
  //   .bundle()
  //   .pipe(source('app.js'))
  //   .pipe(uglify())
  //   .pipe(gulp.dest('./js'));

  var bundleStream = browserify([
    './dev-assets/scripts/main.js'
  ], { debug: true })
  .transform(to5ify)
  .bundle();

  bundleStream
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./js'))
    .pipe(bs.stream());

  done();
})

// ------------------------------------ Gulp Default Behavior
gulp.task('default', gulp.series(['styles','scripts'], function(done) {
    console.log("default");
    done();
}));

// ---------------------------------------------- Gulp Watch
gulp.task('watch:scripts', function () {
  gulp.watch('./dev-assets/scripts/**/*.js', gulp.series('scripts'));
});

gulp.task('watch:styles', function () {
  gulp.watch(paths.sass.src, gulp.series('styles'));
});

gulp.task('watch:templates', function () {
  gulp.watch('./templates/**/*.html.twig').on('change', bs.reload);
});

gulp.task('watch', gulp.series('styles',
  gulp.parallel(['watch:styles','watch:scripts','watch:templates'])
));

gulp.task('watch-sync', gulp.parallel(['init-live-reload','watch'], function(done) {
    console.log("watch is starting");
    done();
}));
