using Microsoft.UI.Xaml.Controls;
using System;
using System.Diagnostics;
using System.Linq;
using Windows.System;

namespace Sonex.Client.Controls.DataGridView
{
    // Odpowiedzialnosc pliku: wspolne akcje menu kontekstowego niezalezne od obszaru klikniecia.
    public sealed partial class DataGridView
    {
        public void ShowFilters()
        {
            OpenFilterForActiveColumn();
        }

        public void ClearFilters()
        {
            ClearAllFilters();
        }

        private void AppendCommonContextMenuItems(MenuFlyout menu)
        {
            // Sekcja wspólna jest zawsze na dole menu, niezależnie od obszaru kliknięcia.
            if (menu.Items.Count > 0)
            {
                menu.Items.Add(new MenuFlyoutSeparator());
            }

            var hasData = (_ItemsSourceFiltred?.Count ?? 0) > 0 && _Columns.Any(c => !c.IsHiden);
            var hasSelection = HasAnySelection();

            menu.Items.Add(BuildViewSubMenu());
            menu.Items.Add(BuildColumnsFlyoutItem());
            menu.Items.Add(BuildExportSubMenu(selectionOnly: false, hasData: hasData, hasSelection: hasSelection));
            menu.Items.Add(BuildExportSubMenu(selectionOnly: true, hasData: hasData, hasSelection: hasSelection));
            menu.Items.Add(CreateContextMenuItem(
                "Save table layout",
                SaveLayoutFromContextMenu,
                Symbol.Save,
                _Columns.Count > 0));
            menu.Items.Add(CreateContextMenuItem(
                "Restore table layout",
                RestoreLayoutFromContextMenu,
                Symbol.Refresh,
                _Columns.Count > 0));
            menu.Items.Add(CreateContextMenuItem(
                "Clear all filters",
                ClearAllFilters,
                "filter.svg",
                _filterRules.Count > 0,
                acceleratorKey: VirtualKey.D,
                acceleratorModifiers: VirtualKeyModifiers.Control | VirtualKeyModifiers.Shift,
                acceleratorText: "Ctrl+Shift+D"));
            menu.Items.Add(CreateContextMenuItem(
                "Show all columns",
                ShowAllColumnsFromContextMenu,
                Symbol.View,
                _Columns.Any(x => x.IsHiden),
                acceleratorKey: VirtualKey.H,
                acceleratorModifiers: VirtualKeyModifiers.Control | VirtualKeyModifiers.Shift,
                acceleratorText: "Ctrl+Shift+H"));
            menu.Items.Add(CreateContextMenuItem(
                "Auto size all columns",
                AutoSizeAllColumnsFromContextMenu,
                "autosize.svg",
                _Columns.Count > 0,
                acceleratorKey: VirtualKey.W,
                acceleratorModifiers: VirtualKeyModifiers.Control | VirtualKeyModifiers.Shift,
                acceleratorText: "Ctrl+Shift+W"));
        }

        private async void SaveLayoutFromContextMenu()
        {
            try
            {
                await SaveLayoutToPreferencesAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[DataGridView] Save layout failed: {ex}");
            }
        }

        private async void RestoreLayoutFromContextMenu()
        {
            try
            {
                await RestoreLayoutFromPreferencesAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[DataGridView] Restore layout failed: {ex}");
            }
        }

        private void ClearAllFilters()
        {
            ApplyColumnFiltersFromFlyout(Array.Empty<FilterRule>());
        }

        private void ShowAllColumnsFromContextMenu()
        {
            var changed = false;
            foreach (var column in _Columns.Where(x => x.IsHiden))
            {
                column.Index -= 1100000;
                changed = true;
            }

            if (!changed)
            {
                return;
            }

            _NeedCalcHeaders = true;
            _NeedCalcHorizontalScroll = true;
            RequestRender();
        }

        private void AutoSizeAllColumnsFromContextMenu()
        {
            if (_Columns.Count == 0)
            {
                return;
            }

            foreach (var column in _Columns)
            {
                column.AutoSize();
            }

            _NeedCalcHeaders = true;
            _NeedCalcHorizontalScroll = true;
            RequestRender();
        }
    }
}
