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

const cssLoaders = function () {
  const sourceMap = process.env.NODE_ENV === 'production';

  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'),
    });
  };
};

exports.envs = function () {
  const env = path.join(__dirname, '../.env');
  const envFiles = [
    `${env}.${process.env.NODE_ENV}`,
    `${env}`,
  ];
  envFiles.forEach((path) => {
    if (fs.existsSync(path)) {
      require('dotenv-expand')(
        require('dotenv').config({
          path,
        }),
      );
    }
  });

  const reg = /^DAMO_APP_/;
  const stringified = Object.keys(process.env)
    .filter((key) => reg.test(key))
    .reduce((env, key) => {
      env[`process.env.${key}`] = JSON.stringify(process.env[key]);
      return env;
    }, {});

  console.log(stringified);
  return stringified;
};

exports.hasFile = function (dir) {
  let result = false;
  if (!fs.existsSync(dir)) return false;
  const paths = fs.readdirSync(path.resolve(dir));
  if (paths.length === 0) return false;
  paths.forEach(el => {
    const _src = path.join(dir, el);
    const stats = fs.statSync(_src);
    if (stats.isFile()) {
      result = true;
    } else if (stats.isDirectory()) {
      result = exports.hasFile(_src);
    }
  });
  return result;
};
