"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/web.dom-collections.for-each.js");

require("core-js/modules/es.object.keys.js");

require("core-js/modules/es.promise.js");

require("regenerator-runtime/runtime.js");

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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

var vscode_languageserver_1 = require("vscode-languageserver");

var runner_1 = require("./runner");

function registerDiagnosticsPushSupport(documents, connection, runtime, validate) {
  var pendingValidationRequests = {};
  var validationDelayMs = 500;
  var disposables = []; // The content of a text document has changed. This event is emitted
  // when the text document first opened or when its content has changed.

  documents.onDidChangeContent(function (change) {
    triggerValidation(change.document);
  }, undefined, disposables); // a document has closed: clear all diagnostics

  documents.onDidClose(function (event) {
    cleanPendingValidation(event.document);
    connection.sendDiagnostics({
      uri: event.document.uri,
      diagnostics: []
    });
  }, undefined, disposables);

  function cleanPendingValidation(textDocument) {
    var request = pendingValidationRequests[textDocument.uri];

    if (request) {
      request.dispose();
      delete pendingValidationRequests[textDocument.uri];
    }
  }

  function triggerValidation(textDocument) {
    cleanPendingValidation(textDocument);
    var request = pendingValidationRequests[textDocument.uri] = runtime.timer.setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var diagnostics;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(request === pendingValidationRequests[textDocument.uri])) {
                _context.next = 12;
                break;
              }

              _context.prev = 1;
              _context.next = 4;
              return validate(textDocument);

            case 4:
              diagnostics = _context.sent;

              if (request === pendingValidationRequests[textDocument.uri]) {
                connection.sendDiagnostics({
                  uri: textDocument.uri,
                  diagnostics: diagnostics
                });
              }

              delete pendingValidationRequests[textDocument.uri];
              _context.next = 12;
              break;

            case 9:
              _context.prev = 9;
              _context.t0 = _context["catch"](1);
              connection.console.error((0, runner_1.formatError)("Error while validating ".concat(textDocument.uri), _context.t0));

            case 12:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[1, 9]]);
    })), validationDelayMs);
  }

  return {
    requestRefresh: function requestRefresh() {
      documents.all().forEach(triggerValidation);
    },
    dispose: function dispose() {
      disposables.forEach(function (d) {
        return d.dispose();
      });
      disposables.length = 0;
      var keys = Object.keys(pendingValidationRequests);

      for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
        var key = _keys[_i];
        pendingValidationRequests[key].dispose();
        delete pendingValidationRequests[key];
      }
    }
  };
}

function registerDiagnosticsPullSupport(documents, connection, runtime, validate) {
  function newDocumentDiagnosticReport(diagnostics) {
    return {
      kind: vscode_languageserver_1.DocumentDiagnosticReportKind.Full,
      items: diagnostics
    };
  }

  var registration = connection.languages.diagnostics.on( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(params, token) {
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              return _context3.abrupt("return", (0, runner_1.runSafeAsync)(runtime, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
                var document;
                return regeneratorRuntime.wrap(function _callee2$(_context2) {
                  while (1) {
                    switch (_context2.prev = _context2.next) {
                      case 0:
                        document = documents.get(params.textDocument.uri);

                        if (!document) {
                          _context2.next = 7;
                          break;
                        }

                        _context2.t0 = newDocumentDiagnosticReport;
                        _context2.next = 5;
                        return validate(document);

                      case 5:
                        _context2.t1 = _context2.sent;
                        return _context2.abrupt("return", (0, _context2.t0)(_context2.t1));

                      case 7:
                        return _context2.abrupt("return", newDocumentDiagnosticReport([]));

                      case 8:
                      case "end":
                        return _context2.stop();
                    }
                  }
                }, _callee2);
              })), newDocumentDiagnosticReport([]), "Error while computing diagnostics for ".concat(params.textDocument.uri), token));

            case 1:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

    return function (_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }());

  function requestRefresh() {
    connection.languages.diagnostics.refresh();
  }

  return {
    requestRefresh: requestRefresh,
    dispose: function dispose() {
      registration.dispose();
    }
  };
}