using C4IT.FASD.Base;
using C4IT.FASD.Cockpit.Communication;
using FasdDesktopUi.Basics.Services.RelationService;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics.Services.SupportCaseSearchService
{
    public class SupportCaseSearchService
    {
        private readonly IRelationService _relationService;

        public SupportCaseSearchService(IRelationService relationService)
        {
            _relationService = relationService;
        }

        public static async Task<cFasdApiSearchResultCollection> GetSearchResultsAsync(string searchQuery, CancellationToken token = default)
        {
            Guid? searchId = null;
            try
            {
                searchId = await cFasdCockpitCommunicationBase.Instance.GetSearchResultsStart(searchQuery, token);

                if (searchId is null)
                    return new cFasdApiSearchResultCollection();

                return await cFasdCockpitCommunicationBase.Instance.GetSearchResultsResult(searchId.Value, token);
            }
            catch (TaskCanceledException)
            {
                if (searchId != null)
                    await cFasdCockpitCommunicationBase.Instance.GetSearchResultsStop(searchId.Value, CancellationToken.None);
            }
            catch (Exception ex)
            {
                LogException(ex);
            }

            return new cFasdApiSearchResultCollection();
        }

        public async Task<cF4sdStagedSearchResultRelationTaskId> LoadRelationsAsync(IEnumerable<cFasdApiSearchResultEntry> relatedTo, CancellationToken token = default)
        {
            IRelationService relationService = _relationService.Clone();
            relationService.RelationsFound += HandleRelationsFound;
            return await relationService.LoadRelationsAsync(relatedTo, token);
        }

        private void HandleRelationsFound(object sender, StagedSearchResultRelationsEventArgs e)
        {
            RelationsFound.Invoke(this, e);

            if (e.StagedResultRelations.IsComplete)
                e.RelationService.RelationsFound -= HandleRelationsFound;
        }

        public event EventHandler<StagedSearchResultRelationsEventArgs> RelationsFound;
    }
}
