import clear from 'clear';

// Import helpers
import getDeploymentConfig from '../operations/getDeploymentConfig';
import print from '../helpers/print';
import prompt from '../helpers/prompt';
import exec from '../helpers/exec';

// Import shared types
import Deployment from '../types/Deployment';

/**
 * Choose the number of instances (tasks) for the deployment
 * @author Gabe Abrams
 * @param deployment the currently selected deployment
 */
const setNumInstances = async (deployment: Deployment) => {
  // Show loading indicator
  clear();
  console.log('Loading chosen number of instances...\n');

  // Get environment variables
  const deployConfig = getDeploymentConfig(deployment);

  // Check the number of instances
  const taskCount = deployConfig.taskCount ?? 1; 

  // Print status
  clear();
  print.subtitle('Num Tasks for Deployment:');
  console.log(`Current num tasks to deploy: ${taskCount}`);
  console.log('');
  console.log('New num tasks (leave empty to leave as-is):');
  const newTaskCount = String(prompt('> ', true)).trim();

  // Immediately go back if no new value
  if (newTaskCount.length === 0) {
    return;
  }

  // Check that it's a valid number
  const newTaskCountNum = Number.parseInt(newTaskCount, 10);
  if (Number.isNaN(newTaskCountNum) || newTaskCountNum < 0) {
    clear();
    print.title('Invalid Number of Tasks');
    console.log('');
    print.enterToContinue();
    return;
  }

  // Update the configuration
  clear();
  console.log('Updating config...\n');
  exec(
    `./node_modules/.bin/caccl-deploy update --profile ${deployment.profile} --app ${deployment.app} taskCount "${newTaskCountNum}"`,
    true,
  );

  // Wait extra for caccl deploy
  await new Promise((resolve) => {
    setTimeout(resolve, 2000);
  });

  // Confirm success
  clear();
  print.title(`Number of Tasks Updated Successfully`);
  console.log('');
  print.enterToContinue();
};

export default setNumInstances;
