text: "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  const tslib_1 = require("tslib");
  const chalk_1 = require("chalk");
  const cli_utils_1 = require("@ionic/cli-utils");
  const command_1 = require("@ionic/cli-utils/lib/command");
  const errors_1 = require("@ionic/cli-utils/lib/errors");
  const CHOICE_CREATE_NEW_APP = 'createNewApp';
  const CHOICE_NEVERMIND = 'nevermind';
  let LinkCommand = class LinkCommand extends command_1.Command {
      preRun(inputs, options) {
          return tslib_1.__awaiter(this, void 0, void 0, function* () {
              const { create } = options;
              if (inputs[0] && create) {
                  throw new errors_1.FatalException(`Sorry--cannot use both ${chalk_1.default.green('app_id')} and ${chalk_1.default.green('--create')}. You must either link an existing app or create a new one.`);
              }
              let proAppId = options['pro-id'] || '';
              const config = yield this.env.config.load();
              if (proAppId) {
                  if (config.backend !== cli_utils_1.BACKEND_PRO) {
                      yield this.env.runCommand(['config', 'set', '-g', 'backend', 'pro'], { showExecution: false });
                      this.env.log.nl();
                      this.env.log.info(`${chalk_1.default.bold(chalk_1.default.blue.underline('Welcome to Ionic Pro!') + ' The CLI is now set up to use Ionic Pro services.')}\n` +
                          `You can revert back to Ionic Cloud (legacy) services at any time:\n\n` +
                          `${chalk_1.default.green('ionic config set -g backend legacy')}\n`);
                  }
                  inputs[0] = proAppId;
              }
          });
      }
      run(inputs, options) {
          return tslib_1.__awaiter(this, void 0, void 0, function* () {
              const { promptToLogin } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/session'));
              const { App } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/app'));
              let [appId] = inputs;
              let { create, name } = options;
              const config = yield this.env.config.load();
              const project = yield this.env.project.load();
              if (project.app_id) {
                  if (project.app_id === appId) {
                      this.env.log.info(`Already linked with app ${chalk_1.default.green(appId)}.`);
                      return;
                  }
                  const msg = appId ?
                      `Are you sure you want to link it to ${chalk_1.default.green(appId)} instead?` :
                      `Would you like to link it to a different app?`;
                  const confirm = yield this.env.prompt({
                      type: 'confirm',
                      name: 'confirm',
                      message: `App ID ${chalk_1.default.green(project.app_id)} is already set up with this app. ${msg}`,
                  });
                  if (!confirm) {
                      this.env.log.info('Not linking.');
                      return;
                  }
              }
              if (!(yield this.env.session.isLoggedIn())) {
                  yield promptToLogin(this.env);
              }
              if (config.backend === cli_utils_1.BACKEND_PRO && !config.git.setup) {
                  yield this.env.runCommand(['ssh', 'setup']);
              }
              if (appId) {
                  this.env.tasks.next(`Looking up app ${chalk_1.default.green(appId)}`);
                  const token = yield this.env.session.getAppUserToken(appId);
                  const appUtil = new App(token, this.env.client);
                  yield appUtil.load(appId);
                  this.env.tasks.end();
              }
              else if (!create) {
                  this.env.tasks.next(`Looking up your apps`);
                  let apps = [];
                  const token = yield this.env.session.getUserToken();
                  const appUtil = new App(token, this.env.client);
                  const paginator = yield appUtil.paginate();
                  for (let r of paginator) {
                      const res = yield r;
                      apps = apps.concat(res.data);
                  }
                  this.env.tasks.end();
                  const createAppChoice = {
                      name: 'Create a new app',
                      id: CHOICE_CREATE_NEW_APP,
                  };
                  const neverMindChoice = {
                      name: 'Nevermind',
                      id: CHOICE_NEVERMIND,
                  };
                  const linkedApp = yield this.env.prompt({
                      type: 'list',
                      name: 'linkedApp',
                      message: `Which app would you like to link`,
                      choices: [createAppChoice, ...apps, neverMindChoice].map((app) => ({
                          name: [CHOICE_CREATE_NEW_APP, CHOICE_NEVERMIND].includes(app.id) ? chalk_1.default.bold(app.name) : `${app.name} (${app.id})`,
                          value: app.id
                      }))
                  });
                  appId = linkedApp;
              }
              if (create || appId === CHOICE_CREATE_NEW_APP) {
                  const token = yield this.env.session.getUserToken();
                  if (config.backend === cli_utils_1.BACKEND_PRO) {
                      if (!name) {
                          name = yield this.env.prompt({
                              type: 'input',
                              name: 'name',
                              message: 'Please enter a name for your new app:',
                          });
                      }
                      const appUtil = new App(token, this.env.client);
                      const app = yield appUtil.create({ name: String(name) });
                      appId = app.id;
                      yield this.env.runCommand(['config', 'set', 'app_id', `"${appId}"`, '--json']);
                      yield this.env.runCommand(['git', 'remote']);
                      this.env.log.ok(`Project linked with app ${chalk_1.default.green(appId)}!`);
                  }
                  else {
                      const opn = yield Promise.resolve().then(() => require('opn'));
                      const dashUrl = yield this.env.config.getDashUrl();
                      opn(`${dashUrl}/?user_token=${token}`, { wait: false });
                      this.env.log.info(`Rerun ${chalk_1.default.green(`ionic link`)} to link to the new app.`);
                  }
              }
              else if (appId === CHOICE_NEVERMIND) {
                  this.env.log.info('Not linking app.');
              }
              else {
                  yield this.env.runCommand(['config', 'set', 'app_id', `"${appId}"`, '--json']);
                  if (config.backend === cli_utils_1.BACKEND_PRO) {
                      yield this.env.runCommand(['git', 'remote']);
                  }
                  this.env.log.ok(`Project linked with app ${chalk_1.default.green(appId)}!`);
              }
              yield Promise.all([this.env.config.save(), this.env.project.save()]);
          });
      }
  };
  LinkCommand = tslib_1.__decorate([
      command_1.CommandMetadata({
          name: 'link',
          type: 'project',
          backends: [cli_utils_1.BACKEND_LEGACY, cli_utils_1.BACKEND_PRO],
          description: 'Connect your local app to Ionic',
          longDescription: `
  If you have an app on Ionic, you can link it to this local Ionic project with this command.
  
  Excluding the ${chalk_1.default.green('app_id')} argument looks up your apps on Ionic and prompts you to select one.
  
  This command simply sets the ${chalk_1.default.bold('app_id')} property in ${chalk_1.default.bold('ionic.config.json')} for other commands to read.
    `,
          exampleCommands: ['', 'a1b2c3d4'],
          inputs: [
              {
                  name: 'app_id',
                  description: `The ID of the app to link (e.g. ${chalk_1.default.green('a1b2c3d4')})`,
                  required: false,
              },
          ],
          options: [
              {
                  name: 'name',
                  description: 'The app name to use during the linking of a new app',
              },
              {
                  name: 'create',
                  description: 'Create a new app on Ionic and link it with this local Ionic project',
                  backends: [cli_utils_1.BACKEND_PRO],
                  type: Boolean,
                  visible: false,
              },
              {
                  name: 'pro-id',
                  description: 'Specify an app ID from the Ionic Dashboard to link',
                  visible: false,
              },
          ],
      })
  ], LinkCommand);
  exports.LinkCommand = LinkCommand;
  