import { spawn } from "child_process";
var d = ''

export async function doIt(start) {
  console.log('doIt', start)
  return new Promise((resolve, reject) => {
    var env = { ...process.env };
    var shell = true;
    var timeout = 15000

    //'npm view @sencha/reext versions'
    const npmLogin = spawn('npm', ['view', '@sencha/reext', 'versions'], { timeout: timeout, shell: shell, env: env });
    npmLogin.stdout.on('data', (data) => {
      const output = data.toString();
      d = d + output
    });
    npmLogin.stderr.on('data', (data) => {
      console.log(`npmLogon stderr: ${data}`, 'pink');
    });
    npmLogin.on('close', (code, signal) => {
      //console.log('npmLogon close: ' + code + ' ' + signal)
      var unpublishArray = []
      const versionsArray = d
        .replace(/[\[\]\s']/g, '') // Remove brackets, whitespace, and single quotes
        .split(',') // Split by comma
        .filter(version => version); // Remove empty strings
      versionsArray.forEach((version) => {
        const lastNumber = version.split('.').pop();
        if (parseInt(lastNumber) > start) {
          var s = 'npm unpublish @sencha/reext@' + version
          unpublishArray.push(s)

          //console.log(s);
        }
      });
      if (signal === 'SIGTERM') {
        resolve(unpublishArray)
      }
      else {
        resolve(unpublishArray)
      }
    });
  });
}

export async function unpublishIt(s) {
  return new Promise((resolve, reject) => {
    var env = { ...process.env };
    var shell = true;
    var timeout = 15000

    var csplit = s.split(' ');
    var thecommand = csplit[0];
    var thearguments = csplit.slice(1);

    var options = { timeout: timeout, shell: shell, env: env, cwd: '.', stdio: ['pipe', 'pipe', 'pipe'] };
    var npmLogin = spawn(thecommand, thearguments, options);
    npmLogin.stdout.on('data', (data) => {
      const output = data.toString();
      console.log('data', output)
    });
    npmLogin.stderr.on('data', (data) => {
      console.log(`npmLogon stderr: ${data}`, 'pink');
    });
    npmLogin.on('close', (code, signal) => {
      //console.log('npmLogon close: ' + code + ' ' + signal)
      if (signal === 'SIGTERM') {
        resolve('')
      }
      else {
        resolve('')
      }
    });
  });
}

//function doAsync

var all = await doIt(326)
//console.log('all', all)


// var last = all[all.length - 1]
// console.log('last', last)
// var u = await unpublishIt(last)
// console.log(u)

for (const element of all) {
  console.log('element', element);
  var u = await unpublishIt(element);
  //console.log(u);
}

// await all.forEach(async (element) => {
//   console.log('element', element)
//   var u = await unpublishIt(element)
//   console.log(u)
// })
console.log('done')