using System;
using JsonRpc.Standard.Contracts;
using LanguageServer.VsCode.Contracts;
using Newtonsoft.Json.Linq;

namespace UpsilonLanguageServer.Services
{
    [JsonRpcScope(MethodPrefix = "completionItem/")]
    public class CompletionItemService : UpsilonLanguageServiceBase
    {
        // The request is sent from the client to the server to resolve additional information
        // for a given completion item.
        [JsonRpcMethod(AllowExtensionData = true)]
        public CompletionItem Resolve()
        {
            var item = RequestContext.Request.Parameters.ToObject<CompletionItem>(Utility.CamelCaseJsonSerializer);
            item.InsertText = item.Label;
            if (item.Kind == CompletionItemKind.Function)
            {
                var data = (JObject)item.Data;
                var varcount = data.GetValue("varcount", StringComparison.InvariantCultureIgnoreCase)?.ToObject<int>();
                item.InsertText += "(";
                for (var i = varcount - 1; i >= 0; i--)
                {
                    if (i != varcount - 1)
                        item.InsertText += ", ";
                    item.InsertText += $"${i}";
                }
                item.InsertText += ")";
            }

            item.InsertTextFormat = InsertTextFormat.Snippet;
            return item;
        }
    }
}
