using MathNet.Numerics;
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace BBWY.Client.Converters
{
    public class InputNumberConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value as string;
            if (string.IsNullOrEmpty(strValue))
            {
                return null;
            }
            decimal result;
            if (strValue.IndexOf('.') == strValue.Length - 1 || (strValue.IndexOf('0') == strValue.Length - 1 && strValue.IndexOf('.') != -1) || !decimal.TryParse(strValue, out result))
            {
                return DependencyProperty.UnsetValue;
            }
            return result;

            //if (string.IsNullOrEmpty(strValue))
            //    return DependencyProperty.UnsetValue;
            //if (strValue.EndsWith("."))
            //    return DependencyProperty.UnsetValue;
            //decimal result = 0M;
            //var dotIndex = strValue.IndexOf('.');
            //if (dotIndex == -1)
            //    decimal.TryParse(strValue, out result);
            //else
            //{
            //    //var intValueStr = strValue.Substring(0, dotIndex);
            //    var decimalValueStr = strValue.Substring(dotIndex + 1);

            //    var n = 1M;
            //    if (decimalValueStr.Length == 1)
            //        n = 1.0M;
            //    if (decimalValueStr.Length == 2)
            //        n = 1.00M;
            //    if (decimalValueStr.Length == 3)
            //        n = 1.000M;
            //    if (decimalValueStr.Length == 4)
            //        n = 1.0000M;
            //    if (decimal.TryParse(strValue, out result))
            //        result = decimal.Round(result * n, decimalValueStr.Length);
            //    else
            //        return DependencyProperty.UnsetValue;
            //}
            //return result;
        }
    }
}