using C4IT.FASD.Base;
using C4IT.Logging;
using C4IT.MultiLanguage;
using FasdDesktopUi.Basics.Helper;
using FasdDesktopUi.Basics.Services.RelationService;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics.UiActions
{
    public class cUiProcessSearchRelationAction : cUiActionBase
    {
        private readonly List<cFasdApiSearchResultEntry> _selectedSearchResult;
        private readonly List<cF4sdApiSearchResultRelation> _relations;
        private readonly cF4sdApiSearchResultRelation _selectedRelation;
        private readonly IRelationService _relationService;
        private readonly ISearchUiProvider _searchUiProvider;
        private readonly cSearchHistoryEntryBase _searchHistoryEntry;

        public cUiProcessSearchRelationAction(cSearchHistorySearchResultEntry searchHistoryEntry, cF4sdApiSearchResultRelation selectedRelation, IRelationService relationService, ISearchUiProvider searchUiProvider)
        {
            Name = !string.IsNullOrWhiteSpace(selectedRelation.DisplayName) ? $"{searchHistoryEntry.HeaderText} → {selectedRelation.DisplayName}" : searchHistoryEntry.HeaderText;
            _selectedSearchResult = searchHistoryEntry.SelectedSearchResult;
            _relations = searchHistoryEntry.Relations;
            _selectedRelation = selectedRelation;
            _relationService = relationService;
            _searchUiProvider = searchUiProvider;
            _searchHistoryEntry = searchHistoryEntry;
        }

        public cUiProcessSearchRelationAction(string name, List<cFasdApiSearchResultEntry> selectedSearchResult, List<cF4sdApiSearchResultRelation> relations, cF4sdApiSearchResultRelation selectedRelation, ISearchUiProvider searchUiProvider, cSearchHistoryEntryBase searchHistoryEntry, IRelationService relationService)
        {
            Name = name;
            _selectedSearchResult = selectedSearchResult;
            _relations = relations;
            _selectedRelation = selectedRelation;
            _searchUiProvider = searchUiProvider;
            _searchHistoryEntry = searchHistoryEntry;
            _relationService = relationService;
        }

        public override async Task<bool> RunUiActionAsync(object sender, UIElement UiLocation, bool isDetailedLayout, cSupportCaseDataProvider dataProvider)
        {
            // return false: The search action has finished, the search could be canceled
            // return true: The search action is ongoing

            var CM = MethodBase.GetCurrentMethod();
            LogMethodBegin(CM);
            try
            {
                if (dataProvider != null)
                {
                    Debug.Assert(true, "At this moment, we want to create a new support call, so we must not have a dataProvider");
                    LogEntry("At this moment, we want to create a new support call, so we must not have a dataProvider", LogLevels.Error);
                    return false;
                }

                if (_selectedRelation == null)
                {
                    Debug.Assert(true, "A new support case can't be opend, if we have no selected relation or seach result");
                    LogEntry("A new support case can't be opend, if we have no sselected relation or seach result", LogLevels.Error);
                    return false;
                }

                if (TicketDeepLinkHelper.TryOpenTicketRelationExternally(_selectedRelation))
                    return false;

                // check, if  have an active support case
                var supportCaseActive = dataProvider?.IsActive ?? false;

                // create the search histroy entry
                var _seachHistoryEntry = new cSearchHistoryRelationEntry(Name, _selectedSearchResult, _relations, _selectedRelation, _searchUiProvider);
                cSearchManager.Instance.ReplaceEntry(_seachHistoryEntry, _searchHistoryEntry);

                // show the loading information
                string caseObjectName = _selectedRelation.DisplayName;
                string loadingStatusText = string.Format(cMultiLanguageSupport.GetItem("Searchbar.Loading.CaseData"), caseObjectName);
                _searchUiProvider.ShowLoadingTextItem(loadingStatusText);

                // if we have an opened support case, close it immediately
                if (supportCaseActive)
                {
                    if (!await cSupportCaseDataProvider.SupportTicketActiveNoticeAsync())
                        return false;
                }


                // set the new result menu properies for loading ....
                _seachHistoryEntry.isSeen = true;
                // get the new data provider for the support call informations (get it from the cache or create a new one)
                dataProvider = await cSupportCaseDataProvider.GetDataProviderForAsync(_selectedRelation, _relationService);

                bool shouldLoadRelationsForSelectedRelation = _selectedRelation.Type == enumF4sdSearchResultClass.User;
                if (shouldLoadRelationsForSelectedRelation)
                    StartLoadingRelationsFor(_selectedRelation);

                if (dataProvider is null)
                {
                    Debug.Assert(true, "Could not start a data provider for the selected criterias.");
                    LogEntry("Could not start a data provider for the selected criterias.", LogLevels.Error);
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                LogMethodEnd(CM);
            }

            return false;
        }

        private void StartLoadingRelationsFor(cF4sdApiSearchResultRelation selectedRelation)
        {
            try
            {
                var relationsToReload = new List<cFasdApiSearchResultEntry>() { new cFasdApiSearchResultEntry()
                    {
                        DisplayName = selectedRelation.DisplayName,
                        id = selectedRelation.id,
                        Infos = selectedRelation.Infos,
                        Name = selectedRelation.Name,
                        Status = selectedRelation.Status,
                        Type = selectedRelation.Type
                    } };
                _ = Task.Run(async () => _relationService.LoadRelationsAsync(relationsToReload), CancellationToken.None);
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
    }
}
