/*
 * Copyright (C) 2017, 2018 TypeFox and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 */
import debounce from 'p-debounce';
import { pathToUri, toDiagnostic } from './protocol-translation.js';
class FileDiagnostics {
    constructor(uri, publishDiagnostics, documents, features) {
        this.uri = uri;
        this.publishDiagnostics = publishDiagnostics;
        this.documents = documents;
        this.features = features;
        this.diagnosticsPerKind = new Map();
        this.firePublishDiagnostics = debounce(() => {
            const diagnostics = this.getDiagnostics();
            this.publishDiagnostics({ uri: this.uri, diagnostics });
        }, 50);
    }
    update(kind, diagnostics) {
        this.diagnosticsPerKind.set(kind, diagnostics);
        this.firePublishDiagnostics();
    }
    getDiagnostics() {
        const result = [];
        for (const diagnostics of this.diagnosticsPerKind.values()) {
            for (const diagnostic of diagnostics) {
                result.push(toDiagnostic(diagnostic, this.documents, this.features));
            }
        }
        return result;
    }
}
export class DiagnosticEventQueue {
    constructor(publishDiagnostics, documents, features, logger) {
        this.publishDiagnostics = publishDiagnostics;
        this.documents = documents;
        this.features = features;
        this.logger = logger;
        this.diagnostics = new Map();
        this.ignoredDiagnosticCodes = new Set();
    }
    updateDiagnostics(kind, event) {
        if (!event.body) {
            this.logger.error(`Received empty ${event.event} diagnostics.`);
            return;
        }
        const { file } = event.body;
        let { diagnostics } = event.body;
        if (this.ignoredDiagnosticCodes.size) {
            diagnostics = diagnostics.filter(diagnostic => !this.isDiagnosticIgnored(diagnostic));
        }
        const uri = pathToUri(file, this.documents);
        const diagnosticsForFile = this.diagnostics.get(uri) || new FileDiagnostics(uri, this.publishDiagnostics, this.documents, this.features);
        diagnosticsForFile.update(kind, diagnostics);
        this.diagnostics.set(uri, diagnosticsForFile);
    }
    updateIgnoredDiagnosticCodes(ignoredCodes) {
        this.ignoredDiagnosticCodes = new Set(ignoredCodes);
    }
    getDiagnosticsForFile(file) {
        const uri = pathToUri(file, this.documents);
        return this.diagnostics.get(uri)?.getDiagnostics() || [];
    }
    isDiagnosticIgnored(diagnostic) {
        return diagnostic.code !== undefined && this.ignoredDiagnosticCodes.has(diagnostic.code);
    }
}
//# sourceMappingURL=diagnostic-queue.js.map