var browserSync 	= require('browser-sync');
var connect			= require('gulp-connect-php');
var gulp 			= require('gulp');
var sass        	= require('gulp-sass');
var notify 			= require("gulp-notify");
var sourcemaps  	= require('gulp-sourcemaps');
var autoprefixer	= require('gulp-autoprefixer');
var bulkSass    	= require('gulp-sass-glob-import');
var uglify = require('gulp-uglify-es').default;
var args   			= require('yargs').argv;
var gulpif 			= require('gulp-if');
var concat = require('gulp-concat-util');

var fs = require('fs');
var path = require('path');
var merge = require('merge-stream');


// gulp task --env env

//Tasks:
//Default: Will mount a virtual server to work with BrowserSync.
//wp: Watch and compile assets once the theme is installed.

// Environments
// prod: will minify assets
// dev: won't minify assets

var isProd		 	= args.env === 'prod';
var isDev 			= args.env === 'dev';

// Compile sass into CSS & auto-inject into browsers
gulp.task('scss', function() {
    return gulp.src(['assets/css/scss/app.scss'])
        .pipe(bulkSass())
        .pipe(sourcemaps.init())
		.pipe(gulpif(isProd, sass({outputStyle: 'compressed'}).on('error', function(err) {
            notify().write(err);
            this.emit('end');
        }))) // only minify if production
		.pipe(gulpif(isDev, sass().on('error', function(err) {
            notify().write(err);
            this.emit('end');
        }))) // not minify if development
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(sourcemaps.write('.'))
		.pipe(gulp.dest("assets/css")) // move files to dist folder
        .pipe(browserSync.stream());
});

// Move the javascript files into our /src/js folder
gulp.task('vendor-js', function() {
  return gulp.src(
    [
      'node_modules/jquery/dist/jquery.min.js',
      'node_modules/jquery-ui-dist/jquery-ui.min.js',
      'node_modules/@fortawesome/fontawesome-free/js/all.min.js',
      'node_modules/bootstrap/dist/js/bootstrap.min.js',
      'node_modules/tether/dist/js/tether.min.js',
      'node_modules/slick-carousel/slick/slick.js',
      'node_modules/imgliquid/js/imgLiquid-min.js',
      'node_modules/magnific-popup/dist/jquery.magnific-popup.min.js',
      //'assets/js/dev/vendor/jquery.initialize.min.js',
      'node_modules/jquery-validation/dist/jquery.validate.min.js',
      'node_modules/jquery-validation/dist/additional-methods.min.js'
    ]
  )
  .pipe(concat('vendor.js'))
  .pipe(uglify())
	.pipe(gulp.dest("assets/js"))
  .pipe(browserSync.stream());
});

// gulp.task('custom-js', function() {
//     return gulp.src(['assets/js/main.js'])
// 		.pipe(gulpif(isProd, uglify())) // only minify if production
// 		// .pipe(gulpif(isDev, uglify({compress: false, output: { beautify: true }}))) // not minify if development
// 		.pipe(gulp.dest("assets/js"))
//         .pipe(browserSync.stream());
// });

// gulp.task('custom-js', function () {
//   return gulp.src([
//     //'assets/js/dev/custom/**/*.js',
//     'assets/js/dev/custom/*.js'
//    ])
//   .pipe(gulpif(isProd, uglify()))
//   .pipe(gulpif(isDev, uglify({compress: false, output: { beautify: true }})))
//   // .pipe(rename('custom.js'))
//   .pipe(rename(function (path) {
//     console.log(path);
//     path.basename = "test";
//   }))
//   .pipe(gulp.dest('assets/js'))
//   .pipe(browserSync.stream());;
// });


var devScriptsPath = 'assets/js/dev/custom';
var scriptsPath = 'assets/js';

function getFolders(dir) {
  return fs.readdirSync(dir)
  .filter(function(file) {
    return fs.statSync(path.join(dir, file)).isDirectory();
  });
}

gulp.task('custom-js', function(done) {
  var folders = getFolders(devScriptsPath);
  if (folders.length !== 0){
    var tasks = folders.map(function(folder) {
      return gulp.src(path.join(devScriptsPath, folder, '/**/*.js'))
      // concat into foldername.js
      .pipe(concat(folder + '.js'))
      .pipe(concat.header('jQuery(document).ready(function( $ ) {'))
      .pipe(concat.footer('});'))
      .pipe(gulpif(isProd, uglify()))
      // write to output
      .pipe(gulp.dest(scriptsPath))
    });
  }

  // process all remaining files in devScriptsPath root into main.js file
  var root = gulp.src(path.join(devScriptsPath, '/*.js'))
  .pipe(concat('main.js'))
  .pipe(concat.header('jQuery(document).ready(function( $ ) {'))
  .pipe(concat.footer('});'))
  .pipe(gulpif(isProd, uglify()))
  .pipe(gulp.dest(scriptsPath));
  if (folders.length !== 0){
    return merge(tasks, root);
  }else{
    return root;
  }
});



// Compile templates
gulp.task('templates', function () {
   return gulp.src(['**/*.php'])
   .pipe(browserSync.stream());
})

// Random port generator to work with multiple projects at the same time
var min = 3000;
var max = 4000;
var randomPort = Math.floor(Math.random() * (max - min + 1)) + min;

// Php Server Tasks
gulp.task('connect', function() {
	connect.server({
		stdio: 'ignore',
		base: './',
		port: randomPort,
		keepalive: true
	});
});

// Browser-Sync Tasks
gulp.task('browser-sync',['connect'], function() {
   browserSync({
      proxy: `127.0.0.1:${randomPort}`,
      port: randomPort,
      open: true,
      notify: true
   });
});

// Watch Tasks
gulp.task ('watch', function(){
   gulp.watch('assets/css/scss/**/*.scss', ['scss']);
   gulp.watch('assets/js/dev/custom/**/*.js', ['custom-js']);
   gulp.watch('assets/js/dev/vendor/**/*.js', ['vendor-js']);
   gulp.watch('**/*.php', ['templates']).on('change', function(e) {
    return gulp.src(e.path)
        .pipe(browserSync.reload({stream: true}));
	});
});

// Default
gulp.task('default', ['watch', 'browser-sync', 'scss', 'custom-js', 'vendor-js']);

// Wordpress Installed
gulp.task('wp', ['watch', 'scss', 'custom-js', 'vendor-js']);
