/*global require process module __dirname*/

var gulp = require('gulp');
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var polyGulp = require('poly-theme-cli').gulp;
var gulpConfig = polyGulp.gulpConfig;

var cssSrc = gulpConfig.app + '/css/**/*.css';
var customWebpackConfig = polyGulp.webpackConfig;
customWebpackConfig.entry = {
    "main": "./js/app.js"
};

var plugins = [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.$": "jquery",
        "window.jQuery": "jquery",
        _: "underscore"
    }),
    new ExtractTextPlugin("[name].css", {
        allChunks: true
    })
];

if (process.env.BUILD_ENV === "PRODUCTION") {
    var uglifyJsPlugin = new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    });
    plugins.push(uglifyJsPlugin);
}

customWebpackConfig.plugins = plugins;

customWebpackConfig.module.loaders.push({
        test: /\.js?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
            presets: ['es2015'],
            plugins: ['add-module-exports', 'transform-object-assign']
        }
    },
    {
        test: /\.hb$/i,
        loader: 'raw-loader'
    }
);

customWebpackConfig.output["library"] = "polyLocator";
customWebpackConfig.output["libraryTarget"] = "umd";

customWebpackConfig.resolve.alias["handlebars"] =
    path.join(__dirname, 'node_modules/handlebars/dist/handlebars.js');
customWebpackConfig.resolve.alias["dropdown"] =
    path.join(__dirname, 'node_modules/bootstrap/js/dropdown.js');
customWebpackConfig.resolve.alias["modal"] =
    path.join(__dirname, 'node_modules/bootstrap/js/modal.js');
customWebpackConfig.resolve.alias["bootstrap_css"] =
    path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.css');

gulp.task('clean', function() {
    polyGulp.clean(gulpConfig);
});

gulp.task('html', function() {
    polyGulp.html(gulpConfig);
});

gulp.task('webpack', function() {
    polyGulp.webpack(customWebpackConfig);
});

gulp.task('browserSync', ['build'], function() {
    polyGulp.browserSync(gulpConfig);
});

gulp.task('watch', ['browserSync'], function() {
    gulp.watch(gulpConfig.html.src, ['html']);
    gulp.watch(gulpConfig.js.src, ['webpack']);
    gulp.watch(cssSrc, ['webpack']);
});

gulp.task('build', ['webpack', 'html']);

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