"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/es.promise.js");

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

require("core-js/modules/es.object.freeze.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.registerValidateSupport = registerValidateSupport;

var md = require("vscode-markdown-languageservice");

var vscode_uri_1 = require("vscode-uri");

var dispose_1 = require("../util/dispose");

var defaultDiagnosticOptions = {
  validateFileLinks: md.DiagnosticLevel.ignore,
  validateReferences: md.DiagnosticLevel.ignore,
  validateFragmentLinks: md.DiagnosticLevel.ignore,
  validateMarkdownFileLinkFragments: md.DiagnosticLevel.ignore,
  validateUnusedLinkDefinitions: md.DiagnosticLevel.ignore,
  validateDuplicateLinkDefinitions: md.DiagnosticLevel.ignore,
  ignoreLinks: []
};

function convertDiagnosticLevel(enabled) {
  switch (enabled) {
    case 'error':
      return md.DiagnosticLevel.error;

    case 'warning':
      return md.DiagnosticLevel.warning;

    case 'ignore':
      return md.DiagnosticLevel.ignore;

    case 'hint':
      return md.DiagnosticLevel.hint;

    default:
      return md.DiagnosticLevel.ignore;
  }
}

function getDiagnosticsOptions(config) {
  var settings = config.getSettings();

  if (!settings) {
    return defaultDiagnosticOptions;
  }

  var validateFragmentLinks = convertDiagnosticLevel(settings.markdown.validate.fragmentLinks.enabled);
  return {
    validateFileLinks: convertDiagnosticLevel(settings.markdown.validate.fileLinks.enabled),
    validateReferences: convertDiagnosticLevel(settings.markdown.validate.referenceLinks.enabled),
    validateFragmentLinks: convertDiagnosticLevel(settings.markdown.validate.fragmentLinks.enabled),
    validateMarkdownFileLinkFragments: settings.markdown.validate.fileLinks.markdownFragmentLinks === 'inherit' ? validateFragmentLinks : convertDiagnosticLevel(settings.markdown.validate.fileLinks.markdownFragmentLinks),
    validateUnusedLinkDefinitions: convertDiagnosticLevel(settings.markdown.validate.unusedLinkDefinitions.enabled),
    validateDuplicateLinkDefinitions: convertDiagnosticLevel(settings.markdown.validate.duplicateLinkDefinitions.enabled),
    ignoreLinks: settings.markdown.validate.ignoredLinks
  };
}

function registerValidateSupport(connection, workspace, documents, ls, config, logger) {
  var diagnosticOptions = defaultDiagnosticOptions;

  function updateDiagnosticsSetting() {
    diagnosticOptions = getDiagnosticsOptions(config);
  }

  var subs = [];
  var manager = ls.createPullDiagnosticsManager();
  subs.push(manager);
  subs.push(manager.onLinkedToFileChanged(function () {
    // TODO: We only need to refresh certain files
    connection.languages.diagnostics.refresh();
  }));
  var emptyDiagnosticsResponse = Object.freeze({
    kind: 'full',
    items: []
  });
  connection.languages.diagnostics.on( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(params, token) {
      var _config$getSettings;

      var uri, document, diagnostics;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              logger.log(md.LogLevel.Debug, 'connection.languages.diagnostics.on', {
                document: params.textDocument.uri
              });

              if ((_config$getSettings = config.getSettings()) !== null && _config$getSettings !== void 0 && _config$getSettings.markdown.validate.enabled) {
                _context.next = 3;
                break;
              }

              return _context.abrupt("return", emptyDiagnosticsResponse);

            case 3:
              uri = vscode_uri_1.URI.parse(params.textDocument.uri);

              if (workspace.hasMarkdownDocument(uri)) {
                _context.next = 6;
                break;
              }

              return _context.abrupt("return", emptyDiagnosticsResponse);

            case 6:
              _context.next = 8;
              return workspace.openMarkdownDocument(uri);

            case 8:
              document = _context.sent;

              if (document) {
                _context.next = 11;
                break;
              }

              return _context.abrupt("return", emptyDiagnosticsResponse);

            case 11:
              _context.next = 13;
              return manager.computeDiagnostics(document, diagnosticOptions, token);

            case 13:
              diagnostics = _context.sent;
              return _context.abrupt("return", {
                kind: 'full',
                items: diagnostics
              });

            case 15:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }());
  updateDiagnosticsSetting();
  subs.push(config.onDidChangeConfiguration(function () {
    updateDiagnosticsSetting();
    connection.languages.diagnostics.refresh();
  }));
  subs.push(documents.onDidClose(function (e) {
    manager.disposeDocumentResources(vscode_uri_1.URI.parse(e.document.uri));
  }));
  return {
    dispose: function dispose() {
      (0, dispose_1.disposeAll)(subs);
    }
  };
}