using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Document;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;

namespace NubLang.LSP;

public class DiagnosticsPublisher
{
    private readonly ILanguageServerFacade _server;

    public DiagnosticsPublisher(ILanguageServerFacade server)
    {
        _server = server;
    }

    public void Publish(DocumentUri uri, IEnumerable<Diagnostics.Diagnostic> diagnostics)
    {
        _server.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams
        {
            Uri = uri,
            Diagnostics = new Container<Diagnostic>(diagnostics.Select(MapDiagnostic))
        });
    }

    private static Diagnostic MapDiagnostic(Diagnostics.Diagnostic nubDiagnostic)
    {
        return new Diagnostic
        {
            Severity = nubDiagnostic.Severity switch
            {
                Diagnostics.DiagnosticSeverity.Info => DiagnosticSeverity.Information,
                Diagnostics.DiagnosticSeverity.Warning => DiagnosticSeverity.Warning,
                Diagnostics.DiagnosticSeverity.Error => DiagnosticSeverity.Error,
                _ => null
            },
            Message = $"{nubDiagnostic.Message}\nhelp: {nubDiagnostic.Help}",
            Range = nubDiagnostic.Span.HasValue
                ? new Range(nubDiagnostic.Span.Value.Start.Line, nubDiagnostic.Span.Value.Start.Column, nubDiagnostic.Span.Value.End.Line, nubDiagnostic.Span.Value.Start.Column)
                : new Range(),
        };
    }
}