using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using Xamarin.Forms;

namespace InABox.Mobile
{
    public class UtilityConverterEventArgs : EventArgs
    {
        public object Value { get; private set; }
        public object Parameter { get; private set; }

        public UtilityConverterEventArgs(object value, object parameter)
        {
            Value = value;
            Parameter = parameter;
        }
    }

    public delegate void UtilityCoverterEvent(object sender, UtilityConverterEventArgs args);
    
    public abstract class UtilityConverter<TIn, TOut> : IValueConverter
    {

        public event UtilityCoverterEvent Converting;
        public event UtilityCoverterEvent Deconverting;
        
        protected abstract TOut Convert(TIn value);

        protected virtual TIn Deconvert(TOut value)
        {
            return default;
        }
        
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var typed = value is TIn tin ? tin : default;  
            Converting?.Invoke(this,new UtilityConverterEventArgs(typed, parameter));
            return Convert(typed);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var typed = value is TOut tout ? tout : default;  
            Deconverting?.Invoke(this,new UtilityConverterEventArgs(typed, parameter));
            return Deconvert(typed);
        }
        
    }
}