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

namespace BeWo.Converter
{
    public class DecimalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                if (string.IsNullOrEmpty(parameter as string))
                {
                    string v = value.ToString();

                    // nachfolgende nullen entfernen
                    while (v.Length > 1 && v[v.Length - 1] == '0')
                    {
                        v = v.Substring(0, v.Length - 1);
                    }

                    if (v.Length > 1 && v[v.Length - 1] == ',')
                    {
                        v = v.Substring(0, v.Length - 1);
                    }

                    return v;
                }

                return string.Format((string)parameter, value);
            }

            return string.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!string.IsNullOrEmpty((string)value))
            {
                var t = decimal.Parse((string)value);
                return t;
            }

            return null;
        }
    }
}