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}\n{(nubDiagnostic.Help == null ? "" : $"help: {nubDiagnostic.Help}")}",
            Range = nubDiagnostic.Span.HasValue
                ? new Range(nubDiagnostic.Span.Value.Start.Line - 1, nubDiagnostic.Span.Value.Start.Column - 1, nubDiagnostic.Span.Value.End.Line - 1, nubDiagnostic.Span.Value.End.Column - 1)
                : new Range(),
        };
    }
}