using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JsonRpc.DynamicProxy.Client;
using JsonRpc.Standard.Client;
using JsonRpc.Standard.Contracts;
using LanguageServer.VsCode.Contracts;
using LanguageServer.VsCode.Contracts.Client;
using LanguageServer.VsCode.Server;
using Upsilon.Binder;
using Upsilon.Text;

namespace UpsilonLanguageServer
{
    public class LanguageServerSession
    {
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();

        public LanguageServerSession(JsonRpcClient rpcClient, IJsonRpcContractResolver contractResolver)
        {
            RpcClient = rpcClient ?? throw new ArgumentNullException(nameof(rpcClient));
            var builder = new JsonRpcProxyBuilder {ContractResolver = contractResolver};
            Client = new ClientProxy(builder, rpcClient);
            Documents = new ConcurrentDictionary<Uri, SessionDocument>();
            DiagnosticProvider = new DiagnosticProvider();
        }

        public CancellationToken CancellationToken => _cts.Token;

        public JsonRpcClient RpcClient { get; }

        public ClientProxy Client { get; }

        public ConcurrentDictionary<Uri, SessionDocument> Documents { get; }

        public DiagnosticProvider DiagnosticProvider { get; }

        public LanguageServerSettings Settings { get; set; } = new LanguageServerSettings();

        public void StopServer()
        {
            _cts.Cancel();
        }

    }

    public class SessionDocument
    {
        /// <summary>
        /// Actually makes the changes to the inner document per this milliseconds.
        /// </summary>
        private const int RenderChangesDelay = 100;

        public SessionDocument(TextDocumentItem doc)
        {
            Document = TextDocument.Load<FullTextDocument>(doc);
        }

        private Task _updateChangesDelayTask;

        private readonly object _syncLock = new object();

        private List<TextDocumentContentChangeEvent> _impendingChanges = new List<TextDocumentContentChangeEvent>();

        public event EventHandler DocumentChanged;

        public TextDocument Document { get; set; }

        public BoundScript Bound { get; set; }
        public SourceText SourceText { get; set; }
        public bool IsChanging { get; set; }

        public void NotifyChanges(IEnumerable<TextDocumentContentChangeEvent> changes)
        {
            IsChanging = true;
            lock (_syncLock)
            {
                if (_impendingChanges == null)
                    _impendingChanges = changes.ToList();
                else
                    _impendingChanges.AddRange(changes);
            }
            if (_updateChangesDelayTask == null || _updateChangesDelayTask.IsCompleted)
            {
                _updateChangesDelayTask = Task.Delay(RenderChangesDelay);
                _updateChangesDelayTask.ContinueWith(t => Task.Run((Action)MakeChanges));
            }
        }

        private void MakeChanges()
        {
            List<TextDocumentContentChangeEvent> localChanges;
            lock (_syncLock)
            {
                localChanges = _impendingChanges;
                if (localChanges == null || localChanges.Count == 0) return;
                _impendingChanges = null;
            }
            Document = Document.ApplyChanges(localChanges);
            if (_impendingChanges == null)
            {
                localChanges.Clear();
                lock (_syncLock)
                {
                    if (_impendingChanges == null)
                        _impendingChanges = localChanges;
                }
            }
            OnDocumentChanged();
        }

        protected virtual void OnDocumentChanged()
        {
            DocumentChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}