using C4IT.FASD.Base;
using C4IT.Logging;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using static C4IT.Logging.cLogManager;

namespace C4IT.DataHistoryProvider
{
    public static class cDataHistoryCollectorSearchTaskCache
    {
        private static Dictionary<Guid, cDataHistoryCollectorSearchTaskEntry> taskCache = new Dictionary<Guid, cDataHistoryCollectorSearchTaskEntry>();

        public static Guid AddTask(CancellationTokenSource cancellationToken, Task<cFasdApiSearchResultCollection> task)
        {
            var retVal = Guid.NewGuid();
            lock (taskCache)
                taskCache[retVal] = new cDataHistoryCollectorSearchTaskEntry() { cancellationTokenSource = cancellationToken, task = task };
            return retVal;
        }

        public static void StopTask(Guid taskID)
        {
            cDataHistoryCollectorSearchTaskEntry _taskInfo;

            lock (taskCache)
            {
                if (!taskCache.TryGetValue(taskID, out _taskInfo))
                {
                    LogEntry($"StopSearchTask: Could not find task with ID: {taskID}");
                    return;
                }
                taskCache.Remove(taskID);
            }

            try
            {
                LogEntry($"StopSearchTask: cancelling task: {taskID}");
                _taskInfo.cancellationTokenSource.Cancel(true);
            }
            catch
            {
            }
        }

        public static async Task<cFasdApiSearchResultCollection> GetResultAsync(Guid taskID)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            try
            {
                cDataHistoryCollectorSearchTaskEntry _taskInfo;
                lock (taskCache)
                {
                    if (!taskCache.TryGetValue(taskID, out _taskInfo))
                        return null;
                }

                cFasdApiSearchResultCollection _result = null;

                try
                {
                    _result = await _taskInfo.task;
                }
                catch { }

                lock (taskCache) { taskCache.Remove(taskID); }

                return _result;
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
            }

            return null;

        }
    }

    internal class cDataHistoryCollectorSearchTaskEntry
    {
        public CancellationTokenSource cancellationTokenSource;
        public Task<cFasdApiSearchResultCollection> task;
    }
}
