#!/usr/bin/env node

/**
 * External dependencies
 */
"use strict";

var _graphqlTag = _interopRequireDefault(require("graphql-tag"));

var _command = _interopRequireDefault(require("../lib/cli/command"));

var _api = _interopRequireDefault(require("../lib/api"));

var _tracker = require("../lib/tracker");

var _rollbar = require("../lib/rollbar");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Internal dependencies
 */
(0, _command.default)({
  format: true
}).argv(process.argv, async () => {
  const api = await (0, _api.default)();
  await (0, _tracker.trackEvent)('app_list_command_execute');
  let response;

  try {
    response = await api.query({
      // $FlowFixMe: gql template is not supported by flow
      query: (0, _graphqlTag.default)`query Apps( $first: Int, $after: String ) {
						apps( first: $first, after: $after ) {
							total,
							nextCursor
							edges {
								id,
								name,
								repo
							}
						}
					}`,
      variables: {
        first: 100,
        after: null // TODO make dynamic

      }
    });
  } catch (err) {
    const message = err.toString();
    await (0, _tracker.trackEvent)('app_list_command_fetch_error', {
      error: message
    });

    _rollbar.rollbar.error(err);

    console.log('Failed to fetch apps: %s', message);
    return;
  }

  if (!response || !response.data || !response.data.apps || !response.data.apps.edges || !response.data.apps.edges.length) {
    const message = 'No apps found';
    await (0, _tracker.trackEvent)('app_list_command_fetch_error', {
      error: message
    });
    console.log(message);
    return;
  }

  await (0, _tracker.trackEvent)('app_list_command_success');
  return response.data.apps.edges;
});