using System;
using System.Globalization;
using System.Windows.Data;

namespace Microscopic_Traffic_Simulator.Converters
{
    /// <summary>
    /// Converts enum value to boolean and vice versa.
    /// </summary>
    public class EnumMatchToBooleanConverter : IValueConverter
    {
        /// <summary>
        /// Converts enum value to boolean
        /// </summary>
        /// <param name="value">Value to convert.</param>
        /// <param name="targetType">Type of the source.</param>
        /// <param name="parameter">One of the values defined in enum.</param>
        /// <param name="culture">Culture info instance.</param>
        /// <returns>Converted value as boolean value.</returns>
        public object Convert(object value, Type targetType,
                              object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return false;

            string checkValue = value.ToString();
            string targetValue = parameter.ToString();
            return checkValue.Equals(targetValue,
                     StringComparison.InvariantCultureIgnoreCase);
        }

        /// <summary>
        /// Converts boolean to enum value.
        /// </summary>
        /// <param name="value">Value to convert.</param>
        /// <param name="targetType">Type of the source.</param>
        /// <param name="parameter">One of the values defined in enum.</param>
        /// <param name="culture">Culture info instance.</param>
        /// <returns>Converted value as enum value.</returns>
        public object ConvertBack(object value, Type targetType,
                                  object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return null;

            bool useValue = (bool)value;
            string targetValue = parameter.ToString();
            if (useValue)
                return Enum.Parse(targetType, targetValue);

            return null;
        }
    } 
}
