using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Layout;
using Avalonia.Media;
using Elfisa.Avalonia.ViewModels;

namespace Elfisa.Avalonia.Views;

public partial class ReportsView : UserControl
{
    private ReportsViewModel? _vm;

    public ReportsView()
    {
        InitializeComponent();
        DataContextChanged += OnDataContextChanged;
    }

    private void OnDataContextChanged(object? sender, EventArgs e)
    {
        if (_vm != null) _vm.ColumnsChanged -= RebuildColumns;
        _vm = DataContext as ReportsViewModel;
        if (_vm != null)
        {
            _vm.ColumnsChanged += RebuildColumns;
            RebuildColumns();
        }
    }

    // DataGrid не умеет динамические колонки через биндинг — строим их из VM в коде.
    private void RebuildColumns()
    {
        Grid.Columns.Clear();
        if (_vm == null) return;

        for (int i = 0; i < _vm.Columns.Count; i++)
        {
            int idx = i;
            var c = _vm.Columns[i];
            Grid.Columns.Add(new DataGridTemplateColumn
            {
                Header = c.Header,
                // одна тянущаяся колонка (star) заполняет свободное место, остальные фикс. пиксель
                Width = c.Stretch
                    ? new DataGridLength(1, DataGridLengthUnitType.Star)
                    : new DataGridLength(c.Weight, DataGridLengthUnitType.Pixel),
                MinWidth = 56,
                CellTemplate = new FuncDataTemplate<ReportRow>((row, _) => new TextBlock
                {
                    Text = row?[idx] ?? "",
                    VerticalAlignment = VerticalAlignment.Center,
                    TextAlignment = c.Numeric ? TextAlignment.Right : TextAlignment.Left,
                    TextTrimming = TextTrimming.CharacterEllipsis
                })
            });
        }
    }
}
