const { chalk, log, getRegistryUrl } = require('./common.cjs');
async function main() {
  try {
    // const { execSync } = require('child_process');
    // const path = require('path');
    const fs = require('fs');
    //const {default:chalk} = await import("chalk");
    await log('preinstall.cjs for ' + process.env.npm_package_name + ' started...', 'green')

    const currentWorkingDirectory = process.cwd();
    await log('Current working directory: ' + currentWorkingDirectory);
    //return;
    if (currentWorkingDirectory === '/Users/marcgusmano/@/ReExt/publish/ReExt') {
        await log('not touching package.json');
    }
    else {
      const doCopy = async (foldername) => {
        let promise = new Promise(async (resolve, reject) => {
          var from = './dist/' + foldername;
          var to = '../../../public/' + foldername;
          var isFolderExist = fs.existsSync(to);
          if (isFolderExist === false) {
            await log(foldername + ' folder does not exist, copying to /public folder...');
            fs.cp(from, to, { recursive: true }, async (err) => {
              await log(foldername + ' folder copy completed...');
              if (err) {
                await log('error -' + err + '...\n');
                return reject(err.toString())
              }
              return resolve(0)
            });
          }
          else {
            await log(foldername + ' folder exists - no copy done...');
            return resolve(2)
          }
        })
        let result = await promise;
        return result
      }
      await doCopy('ReExt');
    }

    const senchaRegistryUrl = getRegistryUrl('@sencha');
    await log('@sencha is pointing to ' + chalk['yellow'](senchaRegistryUrl))

    await log('preinstall.cjs for ' + process.env.npm_package_name + ' completed...\n', 'green')
  }
  catch (e) {
    console.log('* ReExt: - error: ' + e.toString())
  }
}
main();
