"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Red Hat, Inc. All rights reserved.
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.YAMLValidation = exports.yamlDiagToLSDiag = void 0;
const vscode_languageserver_types_1 = require("vscode-languageserver-types");
const baseValidator_1 = require("../parser/schemaValidation/baseValidator");
const textBuffer_1 = require("../utils/textBuffer");
const diagnostic_filter_1 = require("../utils/diagnostic-filter");
const yaml_documents_1 = require("../parser/yaml-documents");
const unused_anchors_1 = require("./validation/unused-anchors");
const yaml_style_1 = require("./validation/yaml-style");
const map_key_order_1 = require("./validation/map-key-order");
const modelineUtil_1 = require("./modelineUtil");
const schemaUrls_1 = require("../utils/schemaUrls");
/**
 * Convert a YAMLDocDiagnostic to a language server Diagnostic
 * @param yamlDiag A YAMLDocDiagnostic from the parser
 * @param textDocument TextDocument from the language server client
 */
const yamlDiagToLSDiag = (yamlDiag, textDocument) => {
    const start = textDocument.positionAt(yamlDiag.location.start);
    const range = {
        start,
        end: yamlDiag.location.toLineEnd
            ? vscode_languageserver_types_1.Position.create(start.line, new textBuffer_1.TextBuffer(textDocument).getLineLength(start.line))
            : textDocument.positionAt(yamlDiag.location.end),
    };
    return vscode_languageserver_types_1.Diagnostic.create(range, yamlDiag.message, yamlDiag.severity, yamlDiag.code, baseValidator_1.YAML_SOURCE);
};
exports.yamlDiagToLSDiag = yamlDiagToLSDiag;
class YAMLValidation {
    constructor(schemaService, telemetry) {
        this.schemaService = schemaService;
        this.telemetry = telemetry;
        this.validationEnabled = true;
        this.validators = [];
        this.MATCHES_MULTIPLE = 'Matches multiple schemas when only one must validate.';
    }
    configure(settings) {
        this.validators = [];
        if (settings) {
            this.validationEnabled = settings.validate;
            this.customTags = settings.customTags;
            this.disableAdditionalProperties = settings.disableAdditionalProperties;
            this.yamlVersion = settings.yamlVersion;
            // Add style validator if flow style is set to forbid only.
            if (settings.flowMapping === 'forbid' || settings.flowSequence === 'forbid') {
                this.validators.push(new yaml_style_1.YAMLStyleValidator(settings));
            }
            if (settings.keyOrdering) {
                this.validators.push(new map_key_order_1.MapKeyOrderValidator());
            }
        }
        this.validators.push(new unused_anchors_1.UnusedAnchorsValidator());
    }
    async doValidation(textDocument, isKubernetes = false) {
        if (!this.validationEnabled) {
            return [];
        }
        const validationResult = [];
        let suppressKubernetesMatchesMultiple = isKubernetes;
        try {
            const yamlDocument = yaml_documents_1.yamlDocumentsCache.getYamlDocument(textDocument, { customTags: this.customTags, yamlVersion: this.yamlVersion }, true);
            for (const [index, currentYAMLDoc] of yamlDocument.documents.entries()) {
                const currentDocumentIsKubernetes = isKubernetes || this.hasKubernetesModelineSchema(currentYAMLDoc);
                currentYAMLDoc.isKubernetes = currentDocumentIsKubernetes;
                suppressKubernetesMatchesMultiple = suppressKubernetesMatchesMultiple || currentDocumentIsKubernetes;
                currentYAMLDoc.currentDocIndex = index;
                currentYAMLDoc.disableAdditionalProperties = this.disableAdditionalProperties;
                currentYAMLDoc.uri = textDocument.uri;
                validationResult.push(...currentYAMLDoc.errors, ...currentYAMLDoc.warnings, ...(await this.getSchemaDiagnostics(textDocument, currentYAMLDoc)), ...this.runAdditionalValidators(textDocument, currentYAMLDoc));
            }
        }
        catch (err) {
            this.telemetry?.sendError('yaml.validation.error', err);
        }
        let previousErr;
        const foundSignatures = new Set();
        const duplicateMessagesRemoved = [];
        for (let err of validationResult) {
            /**
             * A patch ontop of the validation that removes the
             * 'Matches many schemas' error for kubernetes
             * for a better user experience.
             */
            if (suppressKubernetesMatchesMultiple && err.message === this.MATCHES_MULTIPLE) {
                continue;
            }
            if (isYAMLDocDiagnostic(err)) {
                err = (0, exports.yamlDiagToLSDiag)(err, textDocument);
            }
            if (!err.source) {
                err.source = baseValidator_1.YAML_SOURCE;
            }
            if (previousErr &&
                previousErr.message === err.message &&
                previousErr.range.end.line === err.range.start.line &&
                Math.abs(previousErr.range.end.character - err.range.end.character) >= 1) {
                previousErr.range.end = err.range.end;
                continue;
            }
            else {
                previousErr = err;
            }
            const errSig = err.range.start.line + ' ' + err.range.start.character + ' ' + err.message;
            if (!foundSignatures.has(errSig)) {
                duplicateMessagesRemoved.push(err);
                foundSignatures.add(errSig);
            }
        }
        const textBuffer = new textBuffer_1.TextBuffer(textDocument);
        return (0, diagnostic_filter_1.filterSuppressedDiagnostics)(duplicateMessagesRemoved, (d) => d.range.start.line, (d) => d.message, (line) => {
            if (line < 0 || line >= textBuffer.getLineCount()) {
                return undefined;
            }
            return textBuffer.getLineContent(line).replace(/[\r\n]+$/, '');
        });
    }
    hasKubernetesModelineSchema(currentYAMLDoc) {
        const schemaFromModeline = (0, modelineUtil_1.getSchemaFromModeline)(currentYAMLDoc);
        return typeof schemaFromModeline === 'string' && (0, schemaUrls_1.isKubernetes)(schemaFromModeline);
    }
    async getSchemaDiagnostics(textDocument, yamlDocument) {
        const resolvedSchema = await this.schemaService.getSchemaForResource(textDocument.uri, yamlDocument);
        if (!resolvedSchema) {
            return [];
        }
        const diagnostics = [];
        const addSchemaProblem = (errorMessage, errorCode, relatedInformation) => {
            if (!yamlDocument.root) {
                return;
            }
            const astRoot = yamlDocument.root;
            const property = astRoot.type === 'object' ? astRoot.properties[0] : undefined;
            if (property && property.keyNode.value === '$schema') {
                const node = property.valueNode || property;
                const range = vscode_languageserver_types_1.Range.create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
                diagnostics.push(vscode_languageserver_types_1.Diagnostic.create(range, errorMessage, vscode_languageserver_types_1.DiagnosticSeverity.Warning, errorCode, baseValidator_1.YAML_SOURCE, relatedInformation));
            }
            else {
                const range = vscode_languageserver_types_1.Range.create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
                diagnostics.push(vscode_languageserver_types_1.Diagnostic.create(range, errorMessage, vscode_languageserver_types_1.DiagnosticSeverity.Warning, errorCode, baseValidator_1.YAML_SOURCE, relatedInformation));
            }
        };
        if (resolvedSchema.errors.length) {
            const error = resolvedSchema.errors[0];
            addSchemaProblem(error.message, error.code, error.relatedInformation);
        }
        else {
            for (const warning of resolvedSchema.warnings) {
                addSchemaProblem(warning.message, warning.code, warning.relatedInformation);
            }
            const semanticErrors = yamlDocument.validate(textDocument, resolvedSchema.schema);
            if (semanticErrors) {
                diagnostics.push(...semanticErrors);
            }
        }
        return diagnostics;
    }
    runAdditionalValidators(document, yarnDoc) {
        return this.validators.flatMap((validator) => validator.validate(document, yarnDoc));
    }
}
exports.YAMLValidation = YAMLValidation;
function isYAMLDocDiagnostic(diagnostic) {
    return 'location' in diagnostic;
}
//# sourceMappingURL=yamlValidation.js.map