using cfs_tracker.Helpers; using cfs_tracker.ViewModels; using Microsoft.Maui.Controls; using Microsoft.Maui.Graphics; using System; using System.Collections.Specialized; using System.ComponentModel; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace cfs_tracker.Views; public partial class OptionsPage : ContentPage { private static readonly Regex HexColorRegex = new("^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$", RegexOptions.Compiled); private readonly OptionsViewModel _viewModel; private bool _isLoading; private bool _appearanceEditorsBuilt; private bool _appearanceEditorsDirty = true; private AppearanceColorItemViewModel? _dialogItem; private string _dialogInitialHex = string.Empty; private string _dialogWorkingHex = string.Empty; private bool _dialogIsUpdating; public OptionsPage(OptionsViewModel viewModel) { InitializeComponent(); BindingContext = _viewModel = viewModel; _viewModel.AppearanceColors.CollectionChanged += OnAppearanceColorsCollectionChanged; _viewModel.PropertyChanged += OnViewModelPropertyChanged; } protected override async void OnAppearing() { base.OnAppearing(); await LoadPageAsync(); } private async Task LoadPageAsync() { _isLoading = true; _appearanceEditorsDirty = true; _appearanceEditorsBuilt = false; CloseColorDialog(); if (AppearanceColorsHost is not null) AppearanceColorsHost.Children.Clear(); await _viewModel.LoadAsync(); _isLoading = false; EnsureAppearanceEditorsIfNeeded(); } private void OnAppearanceColorsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { _appearanceEditorsDirty = true; if (_isLoading) return; Dispatcher.Dispatch(EnsureAppearanceEditorsIfNeeded); } private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(OptionsViewModel.SelectedTab)) Dispatcher.Dispatch(EnsureAppearanceEditorsIfNeeded); } private void EnsureAppearanceEditorsIfNeeded() { if (AppearanceColorsHost is null) return; if (!_viewModel.IsAppearanceTabSelected) return; if (_appearanceEditorsBuilt && !_appearanceEditorsDirty) return; BuildAppearanceEditors(); } private void BuildAppearanceEditors() { if (AppearanceColorsHost is null) return; AppearanceColorsHost.Children.Clear(); foreach (var item in _viewModel.AppearanceColors) AppearanceColorsHost.Children.Add(CreateColorEditor(item)); _appearanceEditorsBuilt = true; _appearanceEditorsDirty = false; } private View CreateColorEditor(AppearanceColorItemViewModel item) { var normalizedHex = NormalizeHex(item.Value, item.Fallback); item.Value = normalizedHex; item.PreviewColor = ColorUtility.ParseColor(normalizedHex, item.Fallback); var lastValidHex = normalizedHex; var isUpdating = false; var titleLabel = new Label { Text = item.Title, FontAttributes = FontAttributes.Bold, FontSize = 15 }; titleLabel.SetDynamicResource(Label.TextColorProperty, "TextPrimary"); var defaultLabel = new Label { Text = $"Standard: {NormalizeHex(item.Fallback, item.Fallback)}", FontSize = 12 }; defaultLabel.SetDynamicResource(Label.TextColorProperty, "TextMuted"); var hexEntry = new Entry { Placeholder = "#112233", HorizontalOptions = LayoutOptions.Fill, ClearButtonVisibility = ClearButtonVisibility.WhileEditing, BindingContext = item }; hexEntry.SetBinding(Entry.TextProperty, nameof(AppearanceColorItemViewModel.Value), mode: BindingMode.TwoWay); var previewBox = new BoxView { WidthRequest = 64, HeightRequest = 34, CornerRadius = 6, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, BindingContext = item }; previewBox.SetBinding(BoxView.ColorProperty, nameof(AppearanceColorItemViewModel.PreviewColor)); var chooseButton = new Button { Text = "Farbe wählen" }; chooseButton.SetDynamicResource(Button.BackgroundColorProperty, "ButtonSecondaryBackground"); chooseButton.SetDynamicResource(Button.TextColorProperty, "ButtonSecondaryText"); chooseButton.Clicked += (_, _) => OpenColorDialog(item); var editorGrid = new Grid { ColumnSpacing = 10, RowSpacing = 10, ColumnDefinitions = new ColumnDefinitionCollection { new ColumnDefinition { Width = GridLength.Star }, new ColumnDefinition { Width = new GridLength(80) }, new ColumnDefinition { Width = new GridLength(140) } } }; editorGrid.Add(hexEntry); editorGrid.Add(previewBox, 1, 0); editorGrid.Add(chooseButton, 2, 0); if (item is INotifyPropertyChanged notify) { notify.PropertyChanged += (_, args) => { if (args.PropertyName == nameof(AppearanceColorItemViewModel.Value)) lastValidHex = NormalizeHex(item.Value, item.Fallback); }; } hexEntry.TextChanged += (_, args) => { if (isUpdating) return; var text = args.NewTextValue?.Trim() ?? string.Empty; if (!HexColorRegex.IsMatch(text)) return; lastValidHex = NormalizeHex(text, item.Fallback); item.PreviewColor = ColorUtility.ParseColor(lastValidHex, item.Fallback); }; hexEntry.Unfocused += (_, _) => { var text = hexEntry.Text?.Trim() ?? string.Empty; isUpdating = true; if (HexColorRegex.IsMatch(text)) { lastValidHex = NormalizeHex(text, item.Fallback); item.Value = lastValidHex; item.PreviewColor = ColorUtility.ParseColor(lastValidHex, item.Fallback); } else { item.Value = lastValidHex; item.PreviewColor = ColorUtility.ParseColor(lastValidHex, item.Fallback); } isUpdating = false; }; var content = new VerticalStackLayout { Spacing = 8, Children = { titleLabel, defaultLabel, editorGrid } }; var outerBorder = new Border { Padding = new Thickness(10), StrokeThickness = 1, Content = content }; outerBorder.SetDynamicResource(Border.StrokeProperty, "Border"); outerBorder.SetDynamicResource(VisualElement.BackgroundColorProperty, "SurfaceBackgroundAlt"); return outerBorder; } private void OpenColorDialog(AppearanceColorItemViewModel item) { _dialogItem = item; _dialogInitialHex = NormalizeHex(item.Value, item.Fallback); _dialogWorkingHex = _dialogInitialHex; ColorDialogTitleLabel.Text = item.Title; ColorDialogDefaultLabel.Text = $"Standardwert: {NormalizeHex(item.Fallback, item.Fallback)}"; ApplyDialogHex(_dialogWorkingHex, resetBrightness: true); ColorDialogOverlay.IsVisible = true; DialogHexEntry.Focus(); } private void CloseColorDialog() { _dialogItem = null; _dialogInitialHex = string.Empty; _dialogWorkingHex = string.Empty; _dialogIsUpdating = false; if (ColorDialogOverlay is not null) ColorDialogOverlay.IsVisible = false; } private void ApplyDialogHex(string hex, bool resetBrightness) { if (_dialogItem is null) return; var normalizedHex = NormalizeHex(hex, _dialogItem.Fallback); var parsed = ColorUtility.ParseColor(normalizedHex, _dialogItem.Fallback); _dialogIsUpdating = true; DialogHexEntry.Text = normalizedHex; DialogRedSlider.Value = ClampByte(parsed.Red * 255d); DialogGreenSlider.Value = ClampByte(parsed.Green * 255d); DialogBlueSlider.Value = ClampByte(parsed.Blue * 255d); if (resetBrightness) DialogBrightnessSlider.Value = 100; UpdateDialogPreview(normalizedHex); UpdateDialogValueLabels(); _dialogIsUpdating = false; _dialogWorkingHex = normalizedHex; } private void UpdateDialogHexFromSliders() { if (_dialogItem is null || _dialogIsUpdating) return; _dialogIsUpdating = true; var brightnessFactor = DialogBrightnessSlider.Value / 100d; var red = ClampByte(DialogRedSlider.Value * brightnessFactor); var green = ClampByte(DialogGreenSlider.Value * brightnessFactor); var blue = ClampByte(DialogBlueSlider.Value * brightnessFactor); _dialogWorkingHex = $"#{red:X2}{green:X2}{blue:X2}"; DialogHexEntry.Text = _dialogWorkingHex; UpdateDialogPreview(_dialogWorkingHex); UpdateDialogValueLabels(); _dialogIsUpdating = false; } private void UpdateDialogPreview(string hex) { if (_dialogItem is null) return; var normalizedHex = NormalizeHex(hex, _dialogItem.Fallback); var parsed = ColorUtility.ParseColor(normalizedHex, _dialogItem.Fallback); DialogPreviewBorder.BackgroundColor = parsed; DialogPreviewLabel.Text = normalizedHex.ToUpperInvariant(); DialogPreviewLabel.TextColor = GetContrastColor(parsed); } private void UpdateDialogValueLabels() { DialogRedValueLabel.Text = $"{Math.Round(DialogRedSlider.Value):0}"; DialogGreenValueLabel.Text = $"{Math.Round(DialogGreenSlider.Value):0}"; DialogBlueValueLabel.Text = $"{Math.Round(DialogBlueSlider.Value):0}"; DialogBrightnessValueLabel.Text = $"{Math.Round(DialogBrightnessSlider.Value):0}%"; } private void OnDialogHexEntryTextChanged(object? sender, TextChangedEventArgs e) { if (_dialogItem is null || _dialogIsUpdating) return; var text = e.NewTextValue?.Trim() ?? string.Empty; if (!HexColorRegex.IsMatch(text)) return; ApplyDialogHex(text, resetBrightness: true); } private void OnDialogHexEntryUnfocused(object? sender, FocusEventArgs e) { if (_dialogItem is null || _dialogIsUpdating) return; var text = DialogHexEntry.Text?.Trim() ?? string.Empty; if (HexColorRegex.IsMatch(text)) { ApplyDialogHex(text, resetBrightness: true); return; } ApplyDialogHex(_dialogWorkingHex, resetBrightness: false); } private void OnDialogSliderValueChanged(object? sender, ValueChangedEventArgs e) { UpdateDialogHexFromSliders(); } private void OnResetColorDialogClicked(object? sender, EventArgs e) { if (_dialogItem is null) return; ApplyDialogHex(_dialogItem.Fallback, resetBrightness: true); } private void OnCancelColorDialogClicked(object? sender, EventArgs e) { if (_dialogItem is not null) ApplyDialogHex(_dialogInitialHex, resetBrightness: true); CloseColorDialog(); } private void OnApplyColorDialogClicked(object? sender, EventArgs e) { if (_dialogItem is null) return; var finalHex = NormalizeHex(_dialogWorkingHex, _dialogItem.Fallback); _dialogItem.Value = finalHex; _dialogItem.PreviewColor = ColorUtility.ParseColor(finalHex, _dialogItem.Fallback); CloseColorDialog(); } private string NormalizeHex(string? value, string fallback) { var parsed = ColorUtility.ParseColor(value, fallback); var red = ClampByte(parsed.Red * 255d); var green = ClampByte(parsed.Green * 255d); var blue = ClampByte(parsed.Blue * 255d); return $"#{red:X2}{green:X2}{blue:X2}"; } private static int ClampByte(double value) => Math.Clamp((int)Math.Round(value), 0, 255); private static Color GetContrastColor(Color color) { var luminance = (0.299 * color.Red) + (0.587 * color.Green) + (0.114 * color.Blue); return luminance >= 0.6 ? Colors.Black : Colors.White; } }