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

function updateUrlsToStagingInFile(rootPath, filename) {
  return new Promise(function (resolve) {
    try {
      let targetFilePath = path.join(rootPath, filename);

      fs.readFile(targetFilePath, 'utf8', (err, data) => {
        if (err) {
          console.warn(`Unable to find ${chalk.default.yellow(filename)} file at: ${chalk.default.yellow(targetFilePath)}`);
          resolve();
          return;
        }

        data = data.replace(/enplug\.com/ig, 'enplug.in');
        fs.writeFile(targetFilePath, data, 'utf8', (err) => {
          if (err) {
            console.warn(`Unable to replace ${chalk.default.magentaBright('enplug.com')} with ${chalk.default.magentaBright('enplug.in')}`, err);
          }
          resolve();
        });
      });
    } catch (e) {
      console.error(e);
      resolve();
    }
  });
}
/**
 * Updates all instances of enplug.com found in index.html to enplug.in.
 */
function updateUrlsToStaging(rootPath, dirPrefix, nooffline) {
  console.log('Updating URLs to staging');
  const filepath = (file) => dirPrefix ? path.join(dirPrefix, file) : file;

  var updateIndex = updateUrlsToStagingInFile(rootPath, filepath('index.html'));
  var updateOffline = !nooffline
    ? updateUrlsToStagingInFile(rootPath, filepath('enplug-offline-worker.js'))
    : Promise.resolve();

  return Promise.all([updateIndex, updateOffline]);
}

module.exports = updateUrlsToStaging;
