import browserify from 'browserify';
import babelify from 'babelify';
import fs from 'fs';
import del from 'del';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import gulp from 'gulp';
import oghliner from 'oghliner';
import loadPlugins from 'gulp-load-plugins';
const plugins = loadPlugins({
  lazy: false,
});

import babelRegister from 'babel-core/register';
babelRegister();
import sourceMapSupport from 'source-map-support';
sourceMapSupport.install();

import browserSyncCreator from 'browser-sync';
const browserSync = browserSyncCreator.create();

import engine from './engine/index.js';

gulp.task('clean', (done) => {
  del(['./dist']).then(() => {
    done();
  });
});

gulp.task('lint', () => {
  return gulp
    .src(['./*.js', './src/**/*.js'])
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format());
});

gulp.task('test', ['lint']);

gulp.task('deploy', ['build'], () => {
  return oghliner.deploy({
    rootDir: 'dist',
  });
});

gulp.task('build:engine', () => {
  return engine().then((files) => {
    for (const filename of Object.keys(files)) {
      fs.writeFileSync('./dist/' + filename);
    }
  });
});

gulp.task('build:root', ['clean'], () => {
  return gulp
    .src('./src/*.*')
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:js', ['clean'], () => {
  return browserify({
    entries: './src/js/index.js',
    debug: true,
  })
  .transform(babelify.configure())
  .bundle()
  .pipe(source('bundle.js'))
  .pipe(buffer())
  .pipe(plugins.sourcemaps.init({
    loadMaps: true,
  }))
  .pipe(plugins.sourcemaps.write('.'))
  .pipe(gulp.dest('./dist'));
});

gulp.task('build:css', ['clean'], () => {
  return gulp
    .src('./src/css/**/*.css')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.autoprefixer({
      browsers: ['last 2 versions'],
    }))
    .pipe(plugins.concat('bundle.css'))
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest('./dist'));
});

gulp.task('build', ['build:root', 'build:engine', 'build:js', 'build:css']);

gulp.task('watch', ['build'], () => {
  browserSync.init({
    open: false,
    server: {
      baseDir: './dist',
    },
  });
  gulp.watch(['./src/**'], ['build'], browserSync.reload);
});

gulp.task('default', ['build']);

@@ -769,22 +769,36 @@
 js', './
+engine/*.js', './
 src
-/**
 /*.js'%5D)
@@ -1314,27 +1314,16 @@
 ild:js',
- %5B'clean'%5D,
  () =%3E %7B
@@ -1651,27 +1651,16 @@
 ld:css',
- %5B'clean'%5D,
  () =%3E %7B
@@ -1699,11 +1699,8 @@
 ss/*
-*/*
 .css
@@ -2163,16 +2163,17 @@
 './src/*
+.
 *'%5D, %5B'b
@@ -2172,24 +2172,256 @@
 *'%5D, %5B'build
+:root'%5D, browserSync.reload);%0A  gulp.watch(%5B'./src/css/*.css'%5D, %5B'build:css'%5D, browserSync.reload);%0A  gulp.watch(%5B'./src/js/*.js'%5D, %5B'build:js'%5D, browserSync.reload);%0A  gulp.watch(%5B'./engine/*.js', './features/*.md'%5D, %5B'build:engine
 '%5D, browserS

split up watch items for each build:* task. no more clean, should probably be done on initial build.