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

function isLocalOrEnplugUrl(src) {
  return (src.indexOf('//') !== 0 && src.indexOf('http') !== 0) ||
    (src.indexOf('enplug.com') >= 0) ||
    (src.indexOf('enplug.in'));
}

function extractResources(target, file, rx) {
  let match = rx.exec(file);
  while (match != null) {
    let src = match[1]
    // Add local resources and enplug.com files.
    if (isLocalOrEnplugUrl(src)) {
      target.push(src);
    }
    match = rx.exec(file);
  }
}

/**
 * Copies offline support service woker over to the application.
 */
function extractResourcesAndReplaceUrls(offlineConfig, pkg, indexFilePath, srcFilePath, destFilesPaths) {
  return new Promise(resolve => {
    try {
      fs.readFile(indexFilePath, 'utf8', (err, indexFile) => {
        // Generate .css and .js static resources array.
        extractResources(offlineConfig.staticResources, indexFile, new RegExp(/src="(.*?\.js)"/mg));
        extractResources(offlineConfig.staticResources, indexFile, new RegExp(/href="([^"]*?\.css)"/mg));

        console.log('Following static resources have been found:\n', offlineConfig.staticResources);

        fs.readFile(srcFilePath, 'utf8', (err, data) => {
          if (err) {
            console.log(`Unable to read common offline file. Please check if ${chalk.default.green('@enplug/sdk-player')} is installed.`);
            resolve();
            return;
          }
          data = data.replace(/<% config %>/g, JSON.stringify(offlineConfig));
          var offlineServiceWorkerFile = data.replace(/<% app_name %>/g, pkg.name);

          const writes = destFilesPaths.map(dfp => new Promise(resolveItem => {
            fs.writeFile(dfp, offlineServiceWorkerFile, 'utf8', (err) => {
              if (err) { console.log(`Unable to write a common offline service worker file to: ${chalk.default.yellow(dfp)}`); }
              resolveItem();
            });
          }));

          Promise.all(writes).then(resolve);
        });
      });
    } catch (e) {
      console.warn(`Unable to copy offline support service worker. Please check whether ${chalk.default.cyan('offline.config.json')} exists.`);
    }  
  });
}

module.exports = extractResourcesAndReplaceUrls;