'use strict';
const path = require('path');
const packageConfig = require('../package.json');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

exports.assetsPath = function(_path) {
  return path.posix.join('static', _path);
};

const cssLoaders = function () {

  const sourceMap = process.env.NODE_ENV === 'production' ? false : true

  const cssLoader = {
    loader: 'css-loader',
    options: {
      sourceMap
    }
  };

  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap
    }
  };

  function generateLoaders(loader, loaderOptions) {
    const loaders = [cssLoader, postcssLoader]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap
        })
      });
    }
    return [process.env.NODE_ENV === 'production' ? MiniCssExtractPlugin.loader : 'style-loader'].concat(loaders)
  }

  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { sassOptions: { indentedSyntax: true } }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  };
};

exports.styleLoaders = function() {
  const output = [];
  const loaders = cssLoaders();

  for (const extension in loaders) {
    const loader = loaders[extension];
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    });
  }

  return output;
};

exports.createNotifierCallback = () => {
  const notifier = require('node-notifier');

  return (severity, errors) => {
    if (severity !== 'error') return;

    const error = errors[0];
    const filename = error.file && error.file.split('!').pop();

    notifier.notify({
      title: packageConfig.name,
      message: severity + ': ' + error.name,
      subtitle: filename || '',
      icon: path.join(__dirname, 'logo.png')
    });
  };
};
