var config = require('../gulp-tasks-common/development');
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var twig = require('gulp-twig');
var util = require('gulp-util');
var webpack = require('webpack');

var dev = config.dev;

gulp.task('sass-redesign', function () {

  var configSassLocal = {};

  if (dev) {
    configSassLocal.outputStyle = 'expanded';
  }

  gulp.src([
      config.redesignPath + 'scss/**/*.scss'
    ])
    .pipe(sourcemaps.init())
    .pipe(sass(configSassLocal).on('error', sass.logError))
    .pipe(autoprefixer(config.configAutoPrefixer))
    .pipe(sourcemaps.write(''))
    .pipe(gulp.dest(config.redesignDistPath + '/css'));

});

gulp.task('twig-redesign', function () {
  return gulp.src([
      config.redesignPath + 'twig/**/*.twig',
      '!' + config.redesignPath + 'twig/inc/**/*.twig'
    ])
    .pipe(twig({
      data: {}
    }))
    .pipe(gulp.dest(config.redesignDistPath));
});

gulp.task('webpack-redesign', function (callback) {
  webpack({
    devtool: 'source-map',
    entry: {
      'full-fluid': config.redesignPath + 'js/full-fluid'
    },
    output: {
      //path: __dirname,
      path: config.redesignDistPath + '/js',
      publicPath: config.redesignDistPath + '/js/',// cdn, http://...
      filename: '[name].js',
      chunkFilename: '[name].js'
    },
    plugins: [
      // new webpack.optimize.OccurenceOrderPlugin(),
      //new webpack.optimize.UglifyJsPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          exclude: /(node_modules|bower_components)/,
          loader: 'babel',
          query: {
            presets: ['es2015'],
            plugins: ['transform-es2015-parameters', 'transform-runtime'],
            cacheDirectory: true
          }
        }
      ]
    }
  }, function (err, stats) {
    if (err) throw new util.PluginError('webpack', err);
    util.log('[webpack]', stats.toString({
      // output options
    }));
    callback();
  });
});

gulp.task('copy-normalize-redesign', function() {

  gulp.src('./node_modules/normalize.css/normalize.css')
  .pipe(gulp.dest(config.redesignDistPath + ''));

});

gulp.task('watch-redesign', [
  'sass-redesign',
  'twig-redesign',
  'webpack-redesign'
], function () {

  gulp.watch([
    config.redesignPath + 'scss/**/*.scss'
  ], ['sass-redesign']);

  gulp.watch([
    config.redesignPath + 'twig/**/*.twig'
  ], ['twig-redesign']);

  gulp.watch([
    config.redesignPath + 'js/**/*.js'
  ], ['webpack-redesign']);

});
