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';

/**
 * Show and/or modify the deployed branch name or version number
 * @author Gabe Abrams
 * @param deployment the currently selected deployment
 */
const chooseBranch = (deployment: Deployment) => {
  // Show loading indicator
  clear();
  console.log('Loading current target of deployment...\n');

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

  // Get last part of the app image
  const parts = deployConfig.appImage.split(':');
  const branchOrVersion = parts[parts.length - 1];
  const appImagePrefix = deployConfig.appImage.substring(
    0,
    deployConfig.appImage.length - branchOrVersion.length,
  );

  // Check type
  const isVersion = branchOrVersion.includes('.');

  // Process branch name
  const processedBranchName = branchOrVersion.replace('-', '/');

  // Print status
  clear();
  print.subtitle('Target of Deployment:');
  console.log(`Current deployment target: ${isVersion ? `version "${branchOrVersion}" on main branch` : `"${processedBranchName}" branch`}`);
  console.log('');
  console.log('Enter a new branch name or version number (leave empty to go back):');
  const newBranchOrVersion = String(prompt('> ', true)).trim().replace('/', '-');

  // Immediately go back if no new branch name
  if (newBranchOrVersion.length === 0) {
    return;
  }

  // Build a new app image
  const newAppImage = `${appImagePrefix}${newBranchOrVersion}`;

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

  // Confirmation
  clear();
  print.title('Target of Deployment Updated Successfully');
  console.log('');
  print.enterToContinue();
};

export default chooseBranch;
