const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

const packageJSON = require('./package.json');

const IS_PRODUCTION = (process.env['NODE_ENV'] === 'production');
const IS_WDS = (process.env['WDS'] === 'true');
const MODULES_FOLDER = (
  (process.env['YARN_MODULES_FOLDER']) ? process.env['YARN_MODULES_FOLDER'] : 'node_modules'
);

const CONTEXT = path.resolve(__dirname);
const OUTPUT_DIR = path.resolve(CONTEXT, 'frontend');

const settingsContent = fs.readFileSync(path.resolve(CONTEXT, 'settings.js'));
const settingsHash = crypto.createHash('sha1');
settingsHash.update(settingsContent);
const BUILD = settingsHash.digest('hex');

const OUTPUT_FILENAME = `[name]-${BUILD}.js`;
const PUBLIC_PATH = (IS_WDS) ? '/' : '/frontend/';
const VENDOR_PATH = path.resolve('./vendor');

const HOMEHUB_CSS_PATTERN = (IS_PRODUCTION) ? 'homehub.css' : 'homehub.css*';
const HOMEHUB_COMPONENTS_CSS_PATTERN = (
  (IS_PRODUCTION) ? 'homehub-components.css' : 'homehub-components.css*'
);

const copyTransformPath = (targetPath, absolutePath) => {
  return path.basename(targetPath).replace('.css', `-${BUILD}.css`);
};

const copyTransform = (content, absolutePath) => {
  if (IS_PRODUCTION) {
    return content;
  }

  const filename = path.basename(absolutePath);
  const cssFilename = path.basename(filename, '.map');

  const stringContent = content.toString('utf-8').replace(
    cssFilename, cssFilename.replace('.css', `-${BUILD}.css`)
  );

  return stringContent;
};

const config = {
  mode: (IS_PRODUCTION) ? 'production' : 'development',
  devtool: (IS_PRODUCTION) ? false : 'source-map',
  context: CONTEXT,
  entry: {
    homehub: './index.js'
  },
  output: {
    path: OUTPUT_DIR,
    publicPath: PUBLIC_PATH,
    filename: OUTPUT_FILENAME
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        include: VENDOR_PATH,
        use: [
          'babel-loader'
        ]
      },
      {
        test: /\.css?$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  },
  resolve: {
    modules: [MODULES_FOLDER],
    alias: {
      '@bthlabs/homehub-app': path.resolve(
        MODULES_FOLDER, '@bthlabs/homehub-app'
      ),
      '@bthlabs/homehub-components': path.resolve(
        MODULES_FOLDER, '@bthlabs/homehub-components'
      ),
      '@bthlabs/homehub-core': path.resolve(
        MODULES_FOLDER, '@bthlabs/homehub-core'
      ),
      '@bthlabs/homehub-icons': path.resolve(
        MODULES_FOLDER, '@bthlabs/homehub-icons'
      ),
      'prop-types': path.resolve(MODULES_FOLDER, 'prop-types'),
      react: path.resolve(MODULES_FOLDER, 'react'),
      'react-bootstrap': path.resolve(MODULES_FOLDER, 'react-bootstrap'),
      'react-dom': path.resolve(MODULES_FOLDER, 'react-dom'),
      'vendor': VENDOR_PATH
    }
  },
  devServer: {
    disableHostCheck: true,
    host: '10.100.100.101',
    port: 3012,
    proxy: {
      '/backend': 'http://10.100.100.101:3010'
    }
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      PRODUCTION: IS_PRODUCTION
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(CONTEXT, 'templates', 'index.html'),
      templateParameters: {
        build: BUILD,
        version: packageJSON.version,
        publicPath: PUBLIC_PATH
      }
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(
            MODULES_FOLDER, '@bthlabs', 'homehub-app', 'lib',
            HOMEHUB_CSS_PATTERN
          ),
          transformPath: copyTransformPath,
          transform: copyTransform
        }
      ]
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(
            MODULES_FOLDER, '@bthlabs', 'homehub-components', 'lib',
            HOMEHUB_COMPONENTS_CSS_PATTERN
          ),
          transformPath: copyTransformPath,
          transform: copyTransform
        }
      ]
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'assets/icon.png'
        }
      ]
    })
  ]
};

if (IS_PRODUCTION) {
  config.resolve.alias = {
    ...config.resolve.alias,
    'prop-types': path.resolve(MODULES_FOLDER, 'prop-types/prop-types.min.js'),
    'react': path.resolve(MODULES_FOLDER, 'react/umd/react.production.min.js'),
    'react-dom': path.resolve(
      MODULES_FOLDER, 'react-dom/umd/react-dom.production.min.js'
    )
  };
}

module.exports = config;
