import {
  CliLeaf,
  CliFlagInput,
  CliStringArrayInput
} from '@alwaysai/alwayscli';
import { appStartComponent } from '../../components/app';
import { postTrackingDataToHubspot } from '../../infrastructure/post-tracking-data-to-hubspot';

// Currently we run the "start" command as a superuser because otherwise we
// cannot connect to the NCS accelerator. It ~should~ be possible to connect to
// the NCS even without --privileged mode, but we need to do the work to set
// that up. See https://movidius.github.io/ncsdk/docker.html

export const appStartCliLeaf = CliLeaf({
  name: 'start',
  namedInputs: {
    'no-superuser': CliFlagInput({
      description:
        'If running in a container, do so as the login user instead of as the superuser "root"'
    }),
    volumes: CliStringArrayInput({
      description:
        'Volumes to be mounted by Docker. e.g. --volumes /home/user/dir1:/root/dir1 /home/user/dir2:/root/dir2'
    }),
    'env-vars': CliStringArrayInput({
      description:
        'Environment variables to be set within the Docker container. e.g. --env-vars LOG_LEVEL=INFO'
    })
  },
  escapedInput: CliStringArrayInput({
    placeholder: '<args>',
    description: 'Arguments passed directly to the application'
  }),
  description: 'Run this application\'s "start" script',
  async action(_, opts, escaped) {
    const appStartRequest = appStartComponent({
      noSuperuser: opts['no-superuser'],
      volumes: opts.volumes,
      env_vars: opts['env-vars'],
      args: escaped
    });

    const hubSpotTrackingRequest = postTrackingDataToHubspot(
      'started_app',
      true
    );

    const [exitCode] = await Promise.all([
      appStartRequest,
      hubSpotTrackingRequest
    ]);
    process.exit(exitCode);
  }
});
