/* eslint-disable import/no-extraneous-dependencies */
const esbuild = require('esbuild');
const path = require('path');
const fs = require('fs');
const { globSync } = require('glob');
const chalk = require('chalk');
const compileCss = require('./compile-css');
const log = require('./log');

/**
 * Write the CSS file to disk.
 * @param {string} filePath The path to the original SCSS file.
 * @param {string} destination The path to write the CSS file to.
 * @param {object} result The result object from the Sass compiler.
 * @return {void}
 */
function writeCssFile(filePath, destination, result) {
  fs.writeFile(destination, result.css, (err) => {
    if (err) {
      log(`Failed to write '${destination}': ${err}`);
      return;
    }

    if (result.sourceMap) {
      // Write the map file if it's enabled.
      fs.writeFile(`${destination}.map`, JSON.stringify(result.sourceMap), () => {
        if (err) {
          log(`Failed to write '${destination}.map': ${err}`);
          return;
        }

        log(`'${filePath}' is finished.`);
      });
    } else {
      // Attempt to delete any existing sourcemap.
      // We don't care if it fails or not.
      fs.unlink(`${destination}.map`, () => {});

      log(`'${filePath}' is finished.`);
    }
  });
}

log(chalk.green('Building JS files...'));
esbuild.build({
  entryPoints: [path.resolve(__dirname, '../js/**/*.jsx')],
  bundle: false,
  loader: {
    '.json': 'text',
  },
  outdir: path.resolve(__dirname, '../js'),
  banner: {
    js:
      '/**\n * Generated by a build script. Do not modify.\n * Check orginal .jsx file.\n */\n/* eslint-disable */\n',
  },
  // external: ['wp', 'Drupal', 'drupalSettings', 'React', 'ReactDOM', '@wordpress/*'],
});

// Match only on .scss files.
const fileMatch = './css/**/[!_]*.scss';
// Ignore node_modules and vendor folders.
const globOptions = {
  ignore: ['./node_modules/**', './js/vendor/**'],
};

log(chalk.green('Building SASS files...'));

const scssFiles = globSync(fileMatch, globOptions);

scssFiles.forEach(filePath => {
  compileCss(filePath, result => {
    const filename = path.basename(filePath).slice(0, -5);
    const dir = path.dirname(filePath);
    const destination = path.resolve(dir, `${filename}.css`);
    writeCssFile(filePath, destination, result);
  });
});

process.exitCode = 0;