using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using FasdDesktopUi.Basics.Models;
using FasdDesktopUi.Basics.UiActions;
using FasdDesktopUi.Basics.UserControls.AdaptableIcon;
using FasdDesktopUi.Basics;
using FasdDesktopUi.Basics.UserControls;
using F4SD_AdaptableIcon.Enums;

using C4IT.MultiLanguage;
using C4IT.FASD.Base;

using static C4IT.Logging.cLogManager;
using C4IT.FASD.Cockpit.Communication;
using FasdDesktopUi.Basics.Services.SupportCase.Controllers;

namespace FasdDesktopUi.Pages.DetailsPage.UserControls
{
    public partial class DetailsPageNavigationHeading : UserControl
    {
        #region Properties

        private cSupportCaseDataProvider dataProvider;

        public cSupportCaseDataProvider DataProvider
        {
            get => dataProvider; set
            {
                dataProvider = value;
                if (value != null)
                {
                    UpdateHeaderHighlights();
                    SetHeadingVisibility();
                }
            }
        }

        public SupportCaseController SupportCaseController { get; set; }

        private List<Border> _highlightBorders;

        private void UpdateHeaderHighlights()
        {
            try
            {
                foreach (var highlightBorder in _highlightBorders)
                {
                    highlightBorder.ClearValue(BackgroundProperty);

                    bool isEmpty = false;

                    if (highlightBorder == UserStackHighlightBorder)
                        isEmpty = UserTextBlock.Text == cMultiLanguageSupport.GetItem("Header.Select.User");
                    else if (highlightBorder == ComputerStackHighlightBorder)
                        isEmpty = ComputerTextBlock.Text == cMultiLanguageSupport.GetItem("Header.Select.Computer");
                    else if (highlightBorder == VirtualSessionStackHighlightBorder)
                        isEmpty = VirtualSessionTextBlock.Text == cMultiLanguageSupport.GetItem("Header.Select.VirtualSession");
                    else if (highlightBorder == MobileDeviceStackHighlightBorder)
                        isEmpty = MobileDeviceTextBlock.Text == cMultiLanguageSupport.GetItem("Header.Select.MobileDevice");
                    else if (highlightBorder == TicketStackHighlightBorder)
                        isEmpty = TicketTextBlock.Text == cMultiLanguageSupport.GetItem("Header.Select.Ticket") || TicketTextBlock.Text == cMultiLanguageSupport.GetItem("Header.Create.Ticket");
                }

                TicketSwapIcon.ClearValue(AdaptableIcon.IconBackgroundColorProperty);
                ComputerSwapIcon.ClearValue(AdaptableIcon.IconBackgroundColorProperty);

                Border highlightedBorder = null;
                AdaptableIcon swapIcon = null;

                if (DataProvider?.HealthCardDataHelper.SelectedHealthCard?.InformationClasses is null)
                    return;

                if (DataProvider.HealthCardDataHelper.SelectedHealthCard.InformationClasses.Any(identity => identity is enumFasdInformationClass.Ticket))
                {
                    highlightedBorder = TicketStackHighlightBorder;
                    swapIcon = TicketSwapIcon;
                }
                else if (DataProvider.HealthCardDataHelper.SelectedHealthCard.InformationClasses.Any(identity => identity is enumFasdInformationClass.Computer))
                {
                    highlightedBorder = ComputerStackHighlightBorder;
                    swapIcon = ComputerSwapIcon;
                }
                else if (DataProvider.HealthCardDataHelper.SelectedHealthCard.InformationClasses.Any(identity => identity is enumFasdInformationClass.VirtualSession))
                {
                    highlightedBorder = VirtualSessionStackHighlightBorder;
                    swapIcon = VirtualSessionSwapIcon;
                }
                else if (DataProvider.HealthCardDataHelper.SelectedHealthCard.InformationClasses.Any(identity => identity is enumFasdInformationClass.MobileDevice))
                {
                    highlightedBorder = MobileDeviceStackHighlightBorder;
                    swapIcon = MobileDeviceSwapIcon;
                }
                else if (DataProvider.HealthCardDataHelper.SelectedHealthCard.InformationClasses.Any(identity => identity is enumFasdInformationClass.User))
                    highlightedBorder = UserStackHighlightBorder;

                highlightedBorder?.SetResourceReference(BackgroundProperty, "BackgroundColor.Menu.MainCategory");

                swapIcon?.SetResourceReference(AdaptableIcon.IconBackgroundColorProperty, "BackgroundColor.Menu.MainCategory");
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private async Task SetHeadingVisibility()
        {
            try
            {
                if (DataProvider is null)
                    return;
                cCollectorStatusInfo modules = await cFasdCockpitConfig.Instance.CheckCollectorStatusAsync();
                if (modules != null)
                {
                    TicketStack.Visibility = modules.HasM42Config ? Visibility.Visible : Visibility.Collapsed;
                    MobileDeviceStack.Visibility = modules.HasMobileDeviceConfig ? Visibility.Visible : Visibility.Collapsed;
                    VirtualSessionStack.Visibility = modules.HasCitrixConfig ? Visibility.Visible : Visibility.Collapsed;

                    TicketBorder.Visibility = modules.HasM42Config ? Visibility.Visible : Visibility.Collapsed;
                    MobileDeviceBorder.Visibility = modules.HasMobileDeviceConfig ? Visibility.Visible : Visibility.Collapsed;
                    VirtualSessionBorder.Visibility = modules.HasCitrixConfig ? Visibility.Visible : Visibility.Collapsed;

                }

            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public bool ShowsRelations { get; private set; } = false;

        #region HeadingData Dependency Property

        private static void HeadingDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (!(d is DetailsPageNavigationHeading _me))
                    return;

                if (e.NewValue == null)
                    return;

                _me.ResetControl();
                _me.InitializeHeadings();
                _me.UpdateHeaderHighlights();
            }
            catch { }
        }

        public static readonly DependencyProperty HeadingDataProperty =
            DependencyProperty.Register("HeadingData", typeof(List<cHeadingDataModel>), typeof(DetailsPageNavigationHeading), new PropertyMetadata(new List<cHeadingDataModel>(), new PropertyChangedCallback(HeadingDataChanged)));


        public List<cHeadingDataModel> HeadingData
        {
            get { return (List<cHeadingDataModel>)GetValue(HeadingDataProperty); }
            set { SetValue(HeadingDataProperty, value); }
        }

        #endregion

        #region HasDirectConnection

        public bool HasDirectConnection
        {
            get { return (bool)GetValue(HasDirectConnectionProperty); }
            set { SetValue(HasDirectConnectionProperty, value); }
        }

        public static readonly DependencyProperty HasDirectConnectionProperty =
            DependencyProperty.Register("HasDirectConnection", typeof(bool), typeof(DetailsPageNavigationHeading), new PropertyMetadata(false, new PropertyChangedCallback(DirectConnectionStatusChanged)));

        private static void DirectConnectionStatusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is DetailsPageNavigationHeading _me))
                return;

            _me.UpdateDirectConnectionIcon();
        }

        #endregion

        private readonly cHeadingDataModel userDataEmpty = new cHeadingDataModel() { IsOnline = false, InformationClass = enumFasdInformationClass.User, HeadingText = "User auswählen" }; //todo: localize
        private readonly cHeadingDataModel computerDataEmpty = new cHeadingDataModel() { IsOnline = false, InformationClass = enumFasdInformationClass.Computer, HeadingText = cMultiLanguageSupport.GetItem("Header.Select.Computer") };
        private readonly cHeadingDataModel ticketDataEmpty = new cHeadingDataModel() { IsOnline = false, InformationClass = enumFasdInformationClass.Ticket, HeadingText = cMultiLanguageSupport.GetItem("Header.Select.Ticket") };
        private readonly cHeadingDataModel virtualSessionDataEmpty = new cHeadingDataModel() { IsOnline = false, InformationClass = enumFasdInformationClass.VirtualSession, HeadingText = cMultiLanguageSupport.GetItem("Header.Select.VirtualSession") };
        private readonly cHeadingDataModel mobileDeviceDataEmpty = new cHeadingDataModel() { IsOnline = false, InformationClass = enumFasdInformationClass.MobileDevice, HeadingText = cMultiLanguageSupport.GetItem("Header.Select.MobileDevice") };

        #endregion

        public DetailsPageNavigationHeading()
        {
            try
            {
                InitializeComponent();
            }
            catch { }
        }

        protected override void OnInitialized(EventArgs e)
        {
            try
            {
                base.OnInitialized(e);

                ResetControl();

                _highlightBorders = new List<Border>()
                {
                    UserStackHighlightBorder,
                    ComputerStackHighlightBorder,
                    TicketStackHighlightBorder,
                    VirtualSessionStackHighlightBorder,
                    MobileDeviceStackHighlightBorder
                };
            }
            catch { }
        }

        private void ResetControl()
        {
            try
            {
                HeadingScroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;

                UserTextBlock.Text = string.Empty;
                ComputerTextBlock.Text = cMultiLanguageSupport.GetItem("Header.Select.Computer");
                TicketTextBlock.Text = cMultiLanguageSupport.GetItem("Header.Select.Ticket");
                VirtualSessionTextBlock.Text = cMultiLanguageSupport.GetItem("Header.Select.VirtualSession");
                MobileDeviceTextBlock.Text = cMultiLanguageSupport.GetItem("Header.Select.MobileDevice");

                UserIcon.ClearValue(AdaptableIcon.PrimaryIconColorProperty);
                ComputerIcon.ClearValue(AdaptableIcon.PrimaryIconColorProperty);
                TicketIcon.ClearValue(AdaptableIcon.PrimaryIconColorProperty);

                UserIcon.Tag = userDataEmpty.InformationClass;
                ComputerIcon.Tag = computerDataEmpty.InformationClass;
                TicketIcon.Tag = ticketDataEmpty.InformationClass;
                VirtualSessionIcon.Tag = virtualSessionDataEmpty.InformationClass;
                MobileDeviceIcon.Tag = mobileDeviceDataEmpty.InformationClass;

                UserTextBlock.Tag = userDataEmpty.InformationClass;
                ComputerTextBlock.Tag = computerDataEmpty.InformationClass;
                TicketTextBlock.Tag = ticketDataEmpty.InformationClass;
                VirtualSessionTextBlock.Tag = virtualSessionDataEmpty.InformationClass;
                MobileDeviceTextBlock.Tag = mobileDeviceDataEmpty.InformationClass;

                UserTextBlock.ClearValue(StyleProperty);
                ComputerTextBlock.ClearValue(StyleProperty);
                TicketTextBlock.ClearValue(StyleProperty);
                VirtualSessionTextBlock.ClearValue(StyleProperty);
                MobileDeviceTextBlock.ClearValue(StyleProperty);

                ComputerSwapIcon.Tag = computerDataEmpty;
                TicketSwapIcon.Tag = ticketDataEmpty;
                VirtualSessionSwapIcon.Tag = virtualSessionDataEmpty;
                MobileDeviceSwapIcon.Tag = mobileDeviceDataEmpty;

                UserStackHighlightBorder.Tag = userDataEmpty.InformationClass;
                ComputerStackHighlightBorder.Tag = computerDataEmpty.InformationClass;
                TicketStackHighlightBorder.Tag = ticketDataEmpty.InformationClass;
                VirtualSessionStackHighlightBorder.Tag = virtualSessionDataEmpty.InformationClass;
                MobileDeviceStackHighlightBorder.Tag = mobileDeviceDataEmpty.InformationClass;

                ComputerSwapIcon.Style = (Style)FindResource("SwapIconStyle");
                TicketSwapIcon.Style = (Style)FindResource("SwapIconStyle");
                VirtualSessionSwapIcon.Style = (Style)FindResource("SwapIconStyle");
                MobileDeviceSwapIcon.Style = (Style)FindResource("SwapIconStyle");

                ComputerSwapIcon.ClearValue(ToolTipProperty);
                TicketSwapIcon.ClearValue(ToolTipProperty);
                VirtualSessionSwapIcon.ClearValue(ToolTipProperty);
                MobileDeviceSwapIcon.ClearValue(ToolTipProperty);

                SaveTicketIcon.Visibility = Visibility.Collapsed;
                UndoTicketIcon.Visibility = Visibility.Collapsed;

                UserCopyIcon.ClearValue(VisibilityProperty);
                ComputerCopyIcon.ClearValue(VisibilityProperty);
                TicketCopyIcon.ClearValue(VisibilityProperty);
                VirtualSessionCopyIcon.ClearValue(VisibilityProperty);
                MobileDeviceCopyIcon.ClearValue(VisibilityProperty);

                ComputerStackHighlightBorder.MouseLeftButtonUp -= SwapIcon_MouseLeftButtonUp;
                ComputerStackHighlightBorder.TouchDown -= SwapIcon_TouchDown;
                TicketStackHighlightBorder.MouseLeftButtonUp -= SwapIcon_MouseLeftButtonUp;
                TicketStackHighlightBorder.TouchDown -= SwapIcon_TouchDown;
                VirtualSessionStackHighlightBorder.MouseLeftButtonUp -= SwapIcon_MouseLeftButtonUp;
                VirtualSessionStackHighlightBorder.TouchDown -= SwapIcon_TouchDown;
                MobileDeviceStackHighlightBorder.MouseLeftButtonUp -= SwapIcon_MouseLeftButtonUp;
                MobileDeviceStackHighlightBorder.TouchDown -= SwapIcon_TouchDown;

                UserStackHighlightBorder.ClearValue(OpacityProperty);
                ComputerStackHighlightBorder.ClearValue(OpacityProperty);
                TicketStackHighlightBorder.ClearValue(OpacityProperty);
                VirtualSessionStackHighlightBorder.ClearValue(OpacityProperty);
                MobileDeviceStackHighlightBorder.ClearValue(OpacityProperty);

                SetEditMode(false);
                ResetSelectors();
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public void ResetSelectors()
        {
            try
            {
                HeadingScroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                ShowsRelations = false;
                ComputerSelector.MenuDataList = null;
                TicketSelector.MenuDataList = null;
                VirtualSessionSelector.MenuDataList = null;
                MobileDeviceSelector.MenuDataList = null;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void DisableElement(FrameworkElement element, string toolTip)
        {
            try
            {
                element.Style = (Style)FindResource("SwapIconStyleBase");
                element.ToolTip = toolTip;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void InitializeHeadings()
        {
            try
            {
                foreach (var heading in HeadingData)
                {
                    bool hasValue = true;
                    AdaptableIcon headingIcon = null;
                    TextBlock headingTextBlock = null;
                    FrameworkElement highlightBoder = null;
                    AdaptableIcon swapIcon = null;
                    AdaptableIcon copyIcon = null;
                    string disableText = null;

                    switch (heading.InformationClass)
                    {
                        case enumFasdInformationClass.Computer:
                            headingIcon = ComputerIcon;
                            swapIcon = ComputerSwapIcon;
                            headingTextBlock = ComputerTextBlock;
                            copyIcon = ComputerCopyIcon;
                            highlightBoder = ComputerStackHighlightBorder;
                            hasValue = heading.HeadingText != cMultiLanguageSupport.GetItem("Header.Select.Computer");
                            disableText = cMultiLanguageSupport.GetItem("Header.NotFound.Computers");

                            if (!hasValue)
                            {
                                ComputerCopyIcon.Visibility = Visibility.Hidden;
                                ComputerStackHighlightBorder.MouseLeftButtonUp += SwapIcon_MouseLeftButtonUp;
                                ComputerStackHighlightBorder.TouchDown += SwapIcon_TouchDown;
                            }

                            break;
                        case enumFasdInformationClass.VirtualSession:
                            headingIcon = VirtualSessionIcon;
                            swapIcon = VirtualSessionSwapIcon;
                            headingTextBlock = VirtualSessionTextBlock;
                            copyIcon = VirtualSessionCopyIcon;
                            highlightBoder = VirtualSessionStackHighlightBorder;
                            hasValue = heading.HeadingText != cMultiLanguageSupport.GetItem("Header.Select.VirtualSession");
                            disableText = cMultiLanguageSupport.GetItem("Header.NotFound.VirtualSession");

                            if (!hasValue)
                            {
                                VirtualSessionCopyIcon.Visibility = Visibility.Hidden;
                                VirtualSessionStackHighlightBorder.MouseLeftButtonUp += SwapIcon_MouseLeftButtonUp;
                                VirtualSessionStackHighlightBorder.TouchDown += SwapIcon_TouchDown;
                            }
                            if (heading.IsOnline)
                                VirtualSessionIcon.SelectedMaterialIcon = MaterialIcons.MaterialIconType.ic_cloud_queue;
                            else
                                VirtualSessionIcon.SelectedMaterialIcon = MaterialIcons.MaterialIconType.ic_cloud_off;
                            break;

                        case enumFasdInformationClass.MobileDevice:
                            headingIcon = MobileDeviceIcon;
                            swapIcon = MobileDeviceSwapIcon;
                            headingTextBlock = MobileDeviceTextBlock;
                            copyIcon = MobileDeviceCopyIcon;
                            highlightBoder = MobileDeviceStackHighlightBorder;
                            hasValue = heading.HeadingText != cMultiLanguageSupport.GetItem("Header.Select.MobileDevice");
                            disableText = cMultiLanguageSupport.GetItem("Header.NotFound.MobileDevice");

                            if (!hasValue)
                            {
                                MobileDeviceCopyIcon.Visibility = Visibility.Hidden;
                                MobileDeviceStackHighlightBorder.MouseLeftButtonUp += SwapIcon_MouseLeftButtonUp;
                                MobileDeviceStackHighlightBorder.TouchDown += SwapIcon_TouchDown;
                            }

                            break;

                        case enumFasdInformationClass.User:
                            headingIcon = UserIcon;
                            headingTextBlock = UserTextBlock;
                            copyIcon = UserCopyIcon;
                            highlightBoder = UserStackHighlightBorder;
                            hasValue = heading.HeadingText != cMultiLanguageSupport.GetItem("Header.Select.User");

                            if (!hasValue)
                                UserCopyIcon.Visibility = Visibility.Hidden;

                            break;
                        case enumFasdInformationClass.Ticket:
                            headingTextBlock = TicketTextBlock;
                            swapIcon = TicketSwapIcon;

                            if (heading.IsOnline)
                                TicketIcon.SelectedMaterialIcon = MaterialIcons.MaterialIconType.ic_drafts;
                            else
                                TicketIcon.SelectedMaterialIcon = MaterialIcons.MaterialIconType.ic_mail;

                            copyIcon = TicketCopyIcon;
                            highlightBoder = TicketStackHighlightBorder;
                            hasValue = heading.HeadingText != cMultiLanguageSupport.GetItem("Header.Select.Ticket") && heading.HeadingText != cMultiLanguageSupport.GetItem("Header.Create.Ticket");
                            disableText = cMultiLanguageSupport.GetItem("Header.NotFound.Tickets");

                            if (!hasValue)
                            {
                                TicketCopyIcon.Visibility = Visibility.Collapsed;
                                EditTicketIcon.Visibility = Visibility.Collapsed;
                            }

                            if (DataProvider?.CaseRelations?.TryGetValue(heading.InformationClass, out var storedRelations) ?? false)
                                if (storedRelations != null && storedRelations.Count > 0)
                                    break;

                            heading.HeadingText = cMultiLanguageSupport.GetItem("Header.Create.Ticket");
                            break;
                    }

                    if (headingIcon != null)
                    {
                        headingIcon.Tag = heading.Realtion;

                        if (heading.IsOnline)
                        {
                            headingIcon.SetResourceReference(AdaptableIcon.PrimaryIconColorProperty, "Color.Green");
                            headingIcon.ToolTip = cMultiLanguageSupport.GetItem("Header.IsOnline");
                        }
                        else
                        {
                            headingIcon.ClearValue(AdaptableIcon.PrimaryIconColorProperty);
                            headingIcon.ToolTip = cMultiLanguageSupport.GetItem("Header.IsOffline");
                        }
                    }

                    if (headingTextBlock != null && string.IsNullOrWhiteSpace(heading.HeadingText) is false)
                    {
                        headingTextBlock.Tag = heading.Realtion;
                        headingTextBlock.Text = heading.HeadingText;
                    }

                    if (highlightBoder != null)
                    {
                        if (hasValue)
                            highlightBoder.Tag = heading.Realtion;
                        else
                            highlightBoder.Tag = new cSwapCaseInfo() { SelectedCaseInformationClass = heading.InformationClass, HeadingDatas = HeadingData };
                    }

                    if (copyIcon != null)
                    {
                        copyIcon.Tag = heading.HeadingText;

                        if (!hasValue)
                            copyIcon.Visibility = Visibility.Hidden;
                    }

                    if (swapIcon != null)
                    {
                        swapIcon.Tag = new cSwapCaseInfo() { SelectedCaseInformationClass = heading.InformationClass, HeadingDatas = HeadingData };

                        if (DataProvider?.CaseRelations is null || DataProvider.CaseRelations.TryGetValue(heading.InformationClass, out var storedRelations) is false
                            || storedRelations is null || storedRelations.Count == 0)
                        {
                            DisableElement(swapIcon, disableText);
                            headingTextBlock.SetResourceReference(StyleProperty, "DetailsPage.TitleSection.Header.Base");
                            highlightBoder.Opacity = 0.7;

                            highlightBoder.MouseLeftButtonUp -= SwapIcon_MouseLeftButtonUp;
                            highlightBoder.TouchDown -= SwapIcon_TouchDown;
                        }
                        else if (!hasValue)
                        {
                            highlightBoder.MouseLeftButtonUp += SwapIcon_MouseLeftButtonUp;
                            highlightBoder.TouchDown += SwapIcon_TouchDown;
                        }
                    }
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
            }
        }

        private void UpdateDirectConnectionIcon()
        {
            try
            {
                if (HasDirectConnection)
                {
                    ComputerIcon.SelectedInternIcon = enumInternIcons.misc_directConnection;
                    ComputerIcon.IconHeight = 35;
                    ComputerIcon.IconWidth = 35;
                }
                else
                {
                    ComputerIcon.SelectedInternIcon = enumInternIcons.misc_computer;
                    ComputerIcon.ClearValue(AdaptableIcon.IconHeightProperty);
                    ComputerIcon.ClearValue(AdaptableIcon.IconWidthProperty);
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public void SetEditMode(bool isActive)
        {
            try
            {
                EditTicketIcon.Visibility = Visibility.Collapsed;
                SaveTicketIcon.Visibility = Visibility.Collapsed;
                UndoTicketIcon.Visibility = Visibility.Collapsed;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        #region Events

        #region HeadingIcon Click

        public event EventHandler HeadingIconClickedEvent;

        private void HeadingIcon_Click(object sender)
        {
            try
            {
                if (DataProvider.HealthCardDataHelper.IsInEditMode)
                {
                    var dialogResult = CustomMessageBox.CustomMessageBox.Show("Do you want to save changes and continue?", "Open changes", enumHealthCardStateLevel.Warning, Window.GetWindow(this), true);

                    if (dialogResult == false)
                        return;
                    else
                        DataProvider.HealthCardDataHelper.IsInEditMode = false;
                }

                HeadingIconClickedEvent.Invoke(sender, new EventArgs());
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void HeadingIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            HeadingIcon_Click(sender);
        }

        private void HeadingIcon_TouchDown(object sender, TouchEventArgs e)
        {
            HeadingIcon_Click(sender);
        }

        #endregion

        #region SwapIcon Click

        private void SwapIcon_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                if (!(sender is FrameworkElement senderElement))
                    return;

                if (!(senderElement.Tag is cSwapCaseInfo swapCaseData))
                    return;

                CustomMenu location = null;
                ResetSelectors();

                switch (swapCaseData.SelectedCaseInformationClass)
                {
                    case enumFasdInformationClass.Computer:
                        location = ComputerSelector;
                        break;
                    case enumFasdInformationClass.Ticket:
                        location = TicketSelector;
                        break;
                    case enumFasdInformationClass.VirtualSession:
                        location = VirtualSessionSelector;
                        break;
                    case enumFasdInformationClass.MobileDevice:
                        location = MobileDeviceSelector;
                        break;
                    default:
                        break;
                }

                var action = new cShowHeadingSelectionMenuAction();
                ShowsRelations = true;
                cUiActionBase.RaiseEvent(new cShowHeadingSelectionMenuAction(), this, sender);
                DoShowRelations(swapCaseData, location, SupportCaseController);
                e.Handled = true;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }


        private void DoShowRelations(cSwapCaseInfo swapCaseData, CustomMenu customMenu, SupportCaseController supportCaseController)
        {

            var CM = MethodBase.GetCurrentMethod();
            LogMethodBegin(CM);
            try
            {
                var selectedHeadingData = swapCaseData.HeadingDatas.FirstOrDefault(data => data.InformationClass == swapCaseData.SelectedCaseInformationClass);

                if (selectedHeadingData is null)
                    return;

                HeadingScroller.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;

                customMenu.Visibility = Visibility.Visible;

                List<cMenuDataBase> quickActionList = new List<cMenuDataBase>();

                if (dataProvider.CaseRelations != null && dataProvider.CaseRelations.TryGetValue(swapCaseData.SelectedCaseInformationClass, out var storedRelations))
                {
                    foreach (var storedRelation in storedRelations)
                    {
                        bool isMatchingRelation = IsMatchingRelation(storedRelation, swapCaseData.HeadingDatas);
                        quickActionList.Add(new cMenuDataSearchRelation(storedRelation)
                        {
                            IsMatchingRelation = isMatchingRelation,
                            IsUsedForCaseEnrichment = true,
                            UiAction = new cChangeHealthCardAction(storedRelation, supportCaseController)
                        });
                    }
                }
                if (quickActionList.Count > 0)
                    customMenu.MenuDataList = quickActionList;
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                LogMethodEnd(CM);
            }
        }

        private bool IsMatchingRelation(cF4sdApiSearchResultRelation relationData, List<cHeadingDataModel> headingData)
        {
            try
            {
                if (relationData.Type is enumF4sdSearchResultClass.Ticket)
                    if (relationData.Infos.TryGetValue("Asset", out string assetName))
                        return headingData.Any(heading => !string.IsNullOrWhiteSpace(heading.HeadingText) && heading.HeadingText.Equals(assetName));
            }
            catch (Exception E)
            {
                LogException(E);
            }

            return false;
        }

        private void SwapIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SwapIcon_Click(sender, e);
        }

        private void SwapIcon_TouchDown(object sender, TouchEventArgs e)
        {
            SwapIcon_Click(sender, e);
        }

        #endregion

        #region CopyIcon Click

        private async Task CopyIcon_ClickAsync(object sender)
        {

            try
            {
                if (!(sender is AdaptableIcon senderIcon))
                    return;

                if (senderIcon.Tag is null)
                    return;

                System.Windows.Forms.Clipboard.SetText(senderIcon.Tag.ToString());

                await cUtility.ChangeIconToCheckAsync(senderIcon);
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private async void CopyIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) => await CopyIcon_ClickAsync(sender);
        private async void CopyIcon_TouchDown(object sender, TouchEventArgs e) => await CopyIcon_ClickAsync(sender);

        #endregion

        #region EditTicket Click

        private void EditTicketIcon_Click()
        {
            try
            {
                dataProvider.HealthCardDataHelper.IsInEditMode = true;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void EditTicketIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            EditTicketIcon_Click();
        }

        private void EditTicketIcon_TouchDown(object sender, TouchEventArgs e)
        {
            EditTicketIcon_Click();
        }

        #endregion

        #region SaveTicket Click

        private void SaveTicketIcon_Click()
        {
            try
            {
                dataProvider.HealthCardDataHelper.IsInEditMode = false;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void SaveTicketIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SaveTicketIcon_Click();
        }

        private void SaveTicketIcon_TouchDown(object sender, TouchEventArgs e)
        {
            SaveTicketIcon_Click();
        }
        #endregion

        #region UndoTicket Click

        private void UndoTicketIcon_Click()
        {
            try
            {
                var dialogResult = CustomMessageBox.CustomMessageBox.Show("Do you really want to undo changes?\nAll changes will get lost.", "Undo changes", enumHealthCardStateLevel.Error, Window.GetWindow(this), true);

                if (dialogResult is true)
                    dataProvider.HealthCardDataHelper.IsInEditMode = false;
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void UndoTicketIcon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            UndoTicketIcon_Click();
        }

        private void UndoTicketIcon_TouchDown(object sender, TouchEventArgs e)
        {
            UndoTicketIcon_Click();
        }


        #endregion

        #endregion

        // todo hacky solution to toggle blurr border. Think about better solution
        public event EventHandler EmptySpaceClicked;

        private void HeadingBorder_Clicked(object sender, EventArgs e)
        {
            EmptySpaceClicked?.Invoke(this, EventArgs.Empty);
        }
    }
}
