const webpack = require('webpack');
const basePlugins = require('./webpack/plugins');
const loaders = require('./webpack/loaders');

module.exports = function karmaConfig(config) {
  const ciMode = config.singleRun;

  config.set({
    frameworks: ['jasmine'],
    plugins: [
      'karma-jasmine',
      'karma-sourcemap-loader',
      'karma-webpack',
      'karma-phantomjs-launcher',
      ...(ciMode ? ['karma-coverage'] : []),
    ],

    files: [
      './src/karma.entry.js',
    ],
    preprocessors: {
      // Run tests and tested code through webpack to handle template
      // and css imports. Also enable sourcemaps in Karma for more
      // useful error stack traces.
      './src/karma.entry.js': ['webpack', 'sourcemap'],
    },

    webpack: {
      // Used to provide real line numbers for error stack traces.
      // Also used by coverage reporting.
      devtool: 'inline-source-map',
      module: {
        rules: [
          ...loaders,
          ...(ciMode ? [{
            test: /\.js$/,
            exclude: /(test|node_modules)\//,
            use: 'isparta-loader',
          }] : []),
        ],
      },
      plugins: [
        ...basePlugins,
        // Ensure jQuery gets shimmed onto window when running the
        // unit tests or directives that use non-JQLite features will
        // blow up.
        new webpack.ProvidePlugin({
          $: 'jquery',
          jQuery: 'jquery',
          'window.jQuery': 'jquery',
        }),
      ],
    },

    // prevent console spamming when running in Karma.
    webpackServer: { noInfo: true },

    reporters: [
      'progress',
      ...(ciMode ? ['coverage'] : []),
    ],

    coverageReporter: {
      instrumenterOptions: {
        istanbul: { noCompact: true },
      },
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'text-summary' },
        { type: 'lcov', subdir: 'report-lcov' },
      ],
    },

    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: ['PhantomJS'],
  });
};
