const os = require('os');
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
var cmdQueue =   new Array();



function handleStdout(data) {
  var datastr = data.toString('utf8');
  var finished = false;
  if (datastr.match(/Command Start\n/)) {
    datastr = datastr.replace(/Command Start\n/,'');
  } 
  if (datastr.match(/Command End\n/)) {
    datastr = datastr.replace(/Command End\n/,'');
    finished = true;
  }
  if (cmdQueue.length > 0) {
    cmdQueue[0].data+=datastr;
  } 
  if (finished) {
    cmd = cmdQueue.shift();
    if (cmd && cmd.command) {
      if (undefined != typeof cmd.callback) {
        cmd.callback(null, cmd.data);
        processQueue();
      }
    }
  } 
  return datastr;
};


function handleStderr(data) {
  processQueue();
};

function processQueue() {
  if (cmdQueue.length > 0 && cmdQueue[0].state === 'pending') {
    cmdQueue[0].state = 'processing';
    child.stdin.write(cmdQueue[0].command, encoding='utf8');
  }
};


function handleExit(code) {
  console.log('child process exited with code ' + code);
  //process.exit();
};
function getProcessName(binName) {


  const filename = os.platform() === 'win32' ? `${binName}.exe` : binName;
  const filePath = __dirname.includes('asar')
    ? path.join(__dirname, '..', '..', 'assets', 'bin', os.platform(), filename)
    : path.join(__dirname, '..', 'assets', 'bin', os.platform(), filename);
    
 
console.log(fs.existsSync(filePath),path.join(__dirname, '..', 'assets', 'bin', os.platform(), filename));
   
    return fs.existsSync(filePath) ? filePath : filename;
}

async function startChildProcess(name, args, logger) {
  return new Promise((resolve, reject) => {
    const processName = getProcessName(name);
    logger.info(`Using ${name} in path ${processName}`);
    const childProcess = cp.spawn(processName, args);
    childProcess.stdout.on('data', data => {
      logger.info(`${name}: ${data}`);
      //resolve(childProcess);
      resolve(data);
    });
    childProcess.stderr.on('data', data => {
      logger.error(`${name} Error: ${data}`);
      reject(new Error(data));
    });
    childProcess.on('error', reject);
  });
}

function startBlockingProcess(name, args, logger) {
  return new Promise((resolve, reject) => {
    const processName = getProcessName(name);
    logger.info(`Using ${name} in path ${processName}`);
    const childProcess = cp.spawn(processName, args);
    childProcess.stdout.on('data', data => {
      logger.info(`${name}: ${data}`);
    });
    childProcess.stderr.on('data', data => {
      logger.error(`${name} Error: ${data}`);
      reject(new Error(data));
    });
    childProcess.on('exit', resolve);
    childProcess.on('error', reject);
  });
}


module.exports.initPythonProcess = async function({
  args,logger
}) {

 
  console.log('RUNNING Python');
  //logger.error(`started python`);
  const processName = 'python3';

  data = await startChildProcess(processName, args, logger);
  return handleStdout(data);
  
  
//child.stdout.on('data', handleStdout);
//child.stderr.on('data', handleStderr);
//child.on('exit', handleExit);

  
  
  
  
  
  
};


