18d307f52SEvan Baconimport chalk from 'chalk';
28d307f52SEvan Bacon
3*8a424bebSJames Ideimport { Device, logUnauthorized } from './adb';
48d307f52SEvan Baconimport { AbortCommandError } from '../../../utils/errors';
586ab6f9aSEvan Baconimport { createSelectionFilter, promptAsync } from '../../../utils/prompts';
68d307f52SEvan Bacon
78d307f52SEvan Baconfunction nameStyleForDevice(device: Device): (name: string) => string {
88d307f52SEvan Bacon  const isActive = device.isBooted;
98d307f52SEvan Bacon  if (!isActive) {
108d307f52SEvan Bacon    // Use no style changes for a disconnected device that is available to be opened.
118d307f52SEvan Bacon    return (text: string) => text;
128d307f52SEvan Bacon  }
138d307f52SEvan Bacon  // A device that is connected and ready to be used should be bolded to match iOS.
148d307f52SEvan Bacon  if (device.isAuthorized) {
158d307f52SEvan Bacon    return chalk.bold;
168d307f52SEvan Bacon  }
178d307f52SEvan Bacon  // Devices that are unauthorized and connected cannot be used, but they are connected so gray them out.
188d307f52SEvan Bacon  return (text: string) => chalk.bold(chalk.gray(text));
198d307f52SEvan Bacon}
208d307f52SEvan Bacon
2129975bfdSEvan Baconexport async function promptForDeviceAsync(devices: Device[]): Promise<Device> {
228d307f52SEvan Bacon  // TODO: provide an option to add or download more simulators
238d307f52SEvan Bacon
248d307f52SEvan Bacon  const { value } = await promptAsync({
258d307f52SEvan Bacon    type: 'autocomplete',
268d307f52SEvan Bacon    name: 'value',
278d307f52SEvan Bacon    limit: 11,
288d307f52SEvan Bacon    message: 'Select a device/emulator',
298d307f52SEvan Bacon    choices: devices.map((item) => {
308d307f52SEvan Bacon      const format = nameStyleForDevice(item);
318d307f52SEvan Bacon      const type = item.isAuthorized ? item.type : 'unauthorized';
328d307f52SEvan Bacon      return {
338d307f52SEvan Bacon        title: `${format(item.name)} ${chalk.dim(`(${type})`)}`,
348d307f52SEvan Bacon        value: item.name,
358d307f52SEvan Bacon      };
368d307f52SEvan Bacon    }),
3786ab6f9aSEvan Bacon    suggest: createSelectionFilter(),
388d307f52SEvan Bacon  });
398d307f52SEvan Bacon
4029975bfdSEvan Bacon  const device = devices.find(({ name }) => name === value);
418d307f52SEvan Bacon
428d307f52SEvan Bacon  if (device?.isAuthorized === false) {
438d307f52SEvan Bacon    logUnauthorized(device);
448d307f52SEvan Bacon    throw new AbortCommandError();
458d307f52SEvan Bacon  }
468d307f52SEvan Bacon
4729975bfdSEvan Bacon  return device!;
488d307f52SEvan Bacon}
49