import argv  from '../../modules/argv';
import glob from 'glob';
import path from 'path';
import paths from '../common/paths.json';
import pathsModule from '../../modules/paths';
import webpack from 'webpack';
import ConcatPlugin from "webpack-concat-plugin";

/*
 * Constants
 */
const PROJECT_DIR = pathsModule.relocate('./');

/*
 * Functions
 */
const isVendor = (module) => {

  return module.resource && module.resource.indexOf('node_modules') > -1;
};

const getEntries = (globPath) => {

  const files = glob.sync(globPath);
  const entries = {};

  for (let i = 0; i < files.length; i++)
  {
    let entry = files[i];
    entries[path.basename(entry, path.extname(entry))] = entry;
  }
  return entries;
};

const getConfiguration = () => {

  const isDistributableBuild = argv.mode === 'distributable';
  const config = {
    devtool: 'source-map',
    entry: getEntries(PROJECT_DIR + '/' + paths.sources.js.default),
    output: {
      filename: '[name].js'
    },
    module: {
      loaders: [
        {
          test:    /\.jsx?$/,
          exclude: /(node_modules)/,
          loader:  'babel-loader',
          query:   { cacheDirectory: PROJECT_DIR + '/tmp/_babel' }
        },
        {
          test:    /\.json$/,
          exclude: /(node_modules)/,
          loader:  'json-loader'
        },
        {
          test:    /\.html$/,
          exclude: /(node_modules)/,
          loader:  'html-loader?attrs=false'
        }
      ]
    },
    resolve: {
      alias: {

        /*
         * Vendors
         */
        vue: "vue/dist/vue.esm.js",

        /*
         * Directories
         */
        classes: PROJECT_DIR + '/src/js/classes',
        components: PROJECT_DIR + '/src/js/components',
        core: PROJECT_DIR + '/src/js/core',
        modules: PROJECT_DIR + '/src/js/modules'
      }
    }
  };

  const commonsChunkPlugin = new webpack.optimize.CommonsChunkPlugin({
    name: 'vendors',
    minChunks: (module) => isVendor(module),
    filename: '[name].js'
  });

  // NOTE: concats vendors in src/js/vendors directory (legacy vendors)
  const concatPlugin = new ConcatPlugin({
    uglify: false,
    useHash: false,
    sourceMap: false,
    name: 'static-vendors',
    fileName: '[name].js',
    filesToConcat: glob.sync(`${PROJECT_DIR}/src/js/vendors/*.js`)
  });

  if (isDistributableBuild)
  {
    config.module.loaders.push({
      test: /\.js$/,
      exclude: /(node_modules)/,
      loader: 'strip-loader?strip[]=console.log'
    });
    config.plugins = [
      concatPlugin,
      commonsChunkPlugin,
      new webpack.optimize.UglifyJsPlugin()
    ];
  }
  else
  {
    config.plugins = [
      concatPlugin,
      commonsChunkPlugin
    ];
  }
  return config;
};

export default getConfiguration;
