import clear from 'clear';

// Import helpers
import print from '../helpers/print';
import exec from '../helpers/exec';

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

/**
 * Perform a custom deployment now
 * @author Gabe Abrams
 * @param deployment the currently selected deployment
 */
const deployCustomNow = async (deployment: Deployment) => {
  const {
    customStackDeploymentProcess,
  } = config;

  // Run the custom deployment process step by step
  for (const step of customStackDeploymentProcess.steps) {
    if (!step.dontClearBefore) {
      clear();
    }
    
    // Print title
    print.title(step.title);
    console.log('');
    console.log(step.description);
    console.log('');

    // Ask for confirmation
    if (step.askUserBeforeContinuing) {
      print.enterToContinue();
    }

    // Execute the command
    if (step.command) {
      // Inject values into placeholders in the command
      // For example, ${deploymentName} -> deployment.name
      let { command } = step;
      command = command.replace(/\$\{deploymentName\}/g, deployment.name);
      command = command.replace(/\$\{name\}/g, deployment.name);
      command = command.replace(/\$\{deploymentApp\}/g, deployment.app);
      command = command.replace(/\$\{app\}/g, deployment.app);
      command = command.replace(/\$\{deploymentProfile\}/g, deployment.profile);
      command = command.replace(/\$\{profile\}/g, deployment.profile);

      // Run the command
      exec(command, true);
    }
  };
};

export default deployCustomNow;
