"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;

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

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

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

/**
 * External dependencies
 */

/**
 * Internal dependencies
 */
async function _default(app, fields) {
  if (!fields) {
    fields = 'id,name';
  }

  const api = await (0, _api.default)();

  if (isNaN(app)) {
    const res = await api.query({
      // $FlowFixMe: gql template is not supported by flow
      query: (0, _graphqlTag.default)`query App( $name: String ) {
					apps( first: 1, name: $name ) {
						total,
						nextCursor,
						edges {
							${fields}
						}
					}
				}`,
      variables: {
        name: app
      }
    });

    if (!res || !res.data || !res.data.apps || !res.data.apps.edges || !res.data.apps.edges.length) {
      return {};
    }

    return res.data.apps.edges[0];
  }

  app = parseInt(app, 10);
  const res = await api.query({
    // $FlowFixMe: gql template is not supported by flow
    query: (0, _graphqlTag.default)`query App( $id: Int ) {
				app( id: $id ){
					${fields}
				}
			}`,
    variables: {
      id: app
    }
  });

  if (!res || !res.data || !res.data.app) {
    return {};
  }

  return res.data.app;
}