using System;
using System.Windows.Data;

namespace Microscopic_Traffic_Simulator.Converters
{
    /// <summary>
    /// Converter from simulation speed to string.
    /// </summary>
    class FromSimulationSpeedToString : IValueConverter
    {
        /// <summary>
        /// Convert simulation speed to string.
        /// </summary>
        /// <param name="value">Speed.</param>
        /// <param name="targetType">Target type which is string.</param>
        /// <param name="parameter">Parameter defined in UI. Not used.</param>
        /// <param name="culture">Current culture info.</param>
        /// <returns>String representation of simulation speed.</returns>
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            return value.ToString() + "x";
        }

        /// <summary>
        /// Convert string to simulation speed.
        /// </summary>
        /// <param name="value">String of simulation speed.</param>
        /// <param name="targetType">Target type which is double.</param>
        /// <param name="parameter">Parameter defined in UI. Not used.</param>
        /// <param name="culture">Current culture info.</param>
        /// <returns>Simulation speed.</returns>
        public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            string valueString = (string)value;
            double result;
            int suffixLength = 1;
            if (char.IsDigit(valueString[valueString.Length - 1]))
                suffixLength = 0;
            if (double.TryParse(
                valueString.Substring(0, valueString.Length - suffixLength), out result))
            {
                return result;
            }
            else
            {
                return null;
            }
        }
    }
}
