#nullable enable
using System.Globalization;
using Avalonia.Data.Converters;
using CommunityToolkit.Mvvm.ComponentModel;

namespace InABox.Avalonia.Converters
{
    public abstract class AbstractMultiConverter<TIn, TOut> : ObservableObject, IMultiValueConverter
    {
        
        protected abstract TOut Convert(IEnumerable<TIn?>? value, object? parameter = null);

        protected virtual IEnumerable<TIn?>? Deconvert(TOut? value, object? parameter = null)
        {
            return default;
        }
        
        public object?[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            var typed = value is TOut tout ? tout : default;
            var result = Deconvert(typed) ?? [];
            return result.Select(x => x as object).ToArray();
        }

        public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
        {
            if (values?.Any() != true)
                return default(TOut);
            var typed = values.Select(x => x is TIn tin ? tin : default);
            return Convert(typed, parameter);
        }
    }
}