/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * 
 * @format
 */
'use strict';

var fs = require("fs");

var path = require("path");

var _require = require("./GraphQLRelayDirective"),
    SCHEMA_EXTENSION = _require.SCHEMA_EXTENSION;

var _require2 = require("graphql"),
    parse = _require2.parse;

function readSource(sourceFile, basePath) {
  var fullSourceFile = !fs.existsSync(sourceFile) && basePath ? path.join(basePath, sourceFile) : sourceFile;
  return fs.readFileSync(fullSourceFile, 'utf8');
}

function getSchemaIntrospection(schemaPath, basePath) {
  try {
    var schemaPaths = schemaPath.split(',');

    if (schemaPaths.length > 1) {
      return parse(SCHEMA_EXTENSION + '\n' + schemaPaths.map(function (file) {
        return readSource(file, basePath);
      }).join('\n'));
    }

    var source = readSource(schemaPath, basePath);

    if (source[0] === '{') {
      return JSON.parse(source);
    }

    return parse(SCHEMA_EXTENSION + '\n' + source);
  } catch (error) {
    // Log a more helpful warning (by including the schema path).
    console.error('Encountered the following error while loading the GraphQL schema: ' + schemaPath + '\n\n' + error.stack.split('\n').map(function (line) {
      return '> ' + line;
    }).join('\n'));
    throw error;
  }
}

module.exports = getSchemaIntrospection;