'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')

const isDev = process.env.NODE_ENV !== 'production';

const styleRule = (scss) => {
  const test = scss ? /\.scss$/ : /\.css$/;
  let use = [
    {
      loader: 'css-loader',
      // options: {importLoaders: scss ? 3 : 2}
      options: {
        sourceMap: isDev,
        importLoaders: scss ? 2 : 1
      }
    },
    'postcss-loader'
  ];
  if (scss) {
    use = [
      ...use,
      {
        loader: 'sass-loader',
        options: {
          data: process.env.THEME ? `@import "styles/themes/_${process.env.THEME}.scss";` : '',
          sourceMap: isDev
        }
      }
    ]
  }

  if (!isDev) {
    return {
      test,
      loader: ExtractTextPlugin.extract({
        use,
        fallback: 'vue-style-loader'
      })
    }
  } else {
    return {
      test,
      use: [
        'vue-style-loader',
        ...use
      ]
    }
  }
}

const assetsPath = (_path) => {
  const assetsSubDirectory = isDev
    ? config.dev.assetsSubDirectory
    : config.build.assetsSubDirectory

  return path.posix.join(assetsSubDirectory, _path)
}

const 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')
    })
  }
}

module.exports = {
  styleRule,
  isDev,
  assetsPath,
  createNotifierCallback
}
