using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Media; using DesertPaintCodex.Models; using DesertPaintCodex.Services; using System.Text; namespace DesertPaintCodex.Views { public class RecipeView : UserControl { private static readonly SolidColorBrush NoColor = new(); public static readonly DirectProperty ColorProperty = AvaloniaProperty.RegisterDirect(nameof(Color), o => o.Color, (o, v) => o.Color = v); private PaintColor? _color; public PaintColor? Color { get => _color; set => SetAndRaise(ColorProperty, ref _color, value); } public static readonly StyledProperty IngredientsProperty = AvaloniaProperty.Register(nameof(Ingredients)); private string _ingredients = string.Empty; public string Ingredients { get => _ingredients; set => this.SetAndRaise(IngredientsProperty, ref _ingredients, value); } public static readonly DirectProperty RecipeProperty = AvaloniaProperty.RegisterDirect(nameof(Recipe), o => o.Recipe, (o,v) => o.Recipe = v); private PaintRecipe? _recipe; public PaintRecipe? Recipe { get => _recipe; set => this.SetAndRaise(RecipeProperty, ref _recipe, value); } private readonly Border _colorSwatch; private readonly TextBlock _colorName; private readonly TextBlock _ingredientList; private readonly TextBlock _cost; public RecipeView() { InitializeComponent(); _colorSwatch = this.FindControl("ColorSwatch"); _ingredientList = this.FindControl("Ingredients"); _colorName = this.FindControl("ColorName"); _cost = this.FindControl("Cost"); ColorProperty.Changed.AddClassHandler((x, _) => x.UpdateColor()); RecipeProperty.Changed.AddClassHandler((x, _) => x.UpdateRecipe()); UpdateRecipe(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void UpdateColor() { UpdateColorSwatch(); UpdateColorName(); } private void UpdateColorSwatch() { _colorSwatch.Background = Color == null ? NoColor : new SolidColorBrush(new Color(0xFF, Color.Red, Color.Green, Color.Blue)); } private void UpdateColorName() { _colorName.Text = Color == null ? "[Unknown]" : PaletteService.FindNearest(Color); } private void UpdateIngredients() { string ingredients = string.Empty; if (Recipe != null) { StringBuilder sb = new(); for (int i = 0; i < Recipe.Reagents.Count; i++) { sb.Append(Recipe.Reagents[i].Quantity); sb.Append(' '); sb.Append(Recipe.Reagents[i].Name); if (i != Recipe.Reagents.Count - 1) { sb.Append(", "); } } ingredients = sb.ToString(); } _ingredientList.Text = ingredients; } private void UpdateCost() { _cost.Text = Recipe == null ? "Cost: 0" : $"Cost: {Recipe.Cost}"; } private void UpdateRecipe() { if (Recipe != null) { // Update components from recipe Color = Recipe.ReactedColor; } else { Color = null; } UpdateIngredients(); UpdateCost(); } } }