#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xamarin.Forms;

namespace InABox.Mobile
{
    public abstract class AbstractMultiConverter<TIn, TOut> : BindableObject, 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? Convert(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);
        }

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