var gulp = require('gulp');
var gutil = require('gulp-util');
var replace = require('gulp-replace');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var zip = require('gulp-zip');
var del = require('del');
var vinylPaths = require('vinyl-paths');
var runSequence = require('run-sequence');
var program = require('commander');
var spawn = require('child_process').spawn;
var jeditor = require('gulp-json-editor');
var fs = require('fs');

program
  .option('-p, --plugin <name>', 'the name to use for the plugin, overwrites the default')
  .option('-l, --library <name>', 'to export the plugin as a library')
  .parse(process.argv);
var pluginName = program.plugin;

gulp.task('clean', function() {
  return del([
    'dist/*'
  ]);
});

gulp.task('webpack-modern', function(cb) {
  const child = spawn('node', ['node_modules/webpack/bin/webpack.js', '--config', 'build/webpack.prod.conf.js'], {
    env: Object.assign({
      VUE_CLI_MODERN_BUILD: true,
      LIBRARY_NAME: program.library,
    }, process.env),
  });
  child.stdout.on('data', (data) => {
    gutil.log(data.toString());
  });
  child.stderr.on('data', (data) => {
    gutil.log(data.toString());
  });
  child.on('close', (code) => {
    if (code) {
      throw new gutil.PluginError('webpack modern', code);
    }
    cb();
  });
});

gulp.task('webpack-legacy', function(cb) {
  const child = spawn('node', ['node_modules/webpack/bin/webpack.js', '--config', 'build/webpack.prod.conf.js'], {
    env: Object.assign({
      LIBRARY_NAME: program.library,
    }, process.env),
  });
  child.stdout.on('data', (data) => {
    gutil.log(data.toString());
  });
  child.stderr.on('data', (data) => {
    gutil.log(data.toString());
  });
  child.on('close', (code) => {
    if (code) {
      throw new gutil.PluginError('webpack legacy', code);
    }
    cb();
  });
});

gulp.task('uglify-modern', function(cb) { // TODO replace with terser-webpack-plugin when moving to webpack 4
  const child = spawn('node', ['node_modules/terser/bin/uglifyjs', '--mangle', '--output', 'dist/plugin.es6.js', 'dist/plugin._es6.js']);
  child.stdout.on('data', (data) => {
    gutil.log(data.toString());
  });
  child.stderr.on('data', (data) => {
    gutil.log(data.toString());
  });
  child.on('close', (code) => {
    if (code) {
      throw new gutil.PluginError('webpack modern', code);
    }
    fs.unlink('dist/plugin._es6.js', (err) => {
      if (err) {
        throw new guitl.PluginError('webpack modern', err);
      }
      cb();
    });
  });
});

gulp.task('replace', function() {
  return gulp.src(['dist/*.js'])
    .pipe(gulpif(!pluginName, replace(/registerPlugin\((.*)\)/, function(match) {
      pluginName = match.match(/name:"(\w+)"/)[1];
      return match;
    })))
    .pipe(replace(/\.?\/?(assets|img|fonts|media)\//g, function(match, folder) {
      return `plugins/${pluginName}/`;
    }))
    .pipe(vinylPaths(del))
    .pipe(rename(function(path) {
      path.basename = /\.es6$/.test(path.basename) ? `${pluginName}.es6` : pluginName;
    }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('add-esmodule', function() {
  if (!fs.existsSync('config.json')) {
    fs.writeFileSync('config.json', '{}');
  }
  return gulp.src('config.json')
    .pipe(jeditor({
      _esmodule: true,
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('zip', function() {
  return gulp.src(['dist/*.js', 'assets/**/*', 'config.json', 'package.json', 'img/**/*', 'README.md'], { base: process.cwd() })
    .pipe(rename(function (path) {
      var ext = path.dirname !== 'dist' && path.dirname !== '.' ? path.dirname : '';
      path.dirname = pluginName + '/' + ext;
    }))
    .pipe(zip(pluginName + '.zip'))
    .pipe(gulp.dest('dist'));
});

gulp.task('build', function(cb) {
  runSequence(
    'clean',
    'webpack-modern',
    'webpack-legacy',
    'uglify-modern',
    'replace',
    'add-esmodule',
    'zip',
    cb
  );
});

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