using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Browser;
using System.Reflection;
using System.Text;

namespace CalculatedColumns
{
    public class CalculatingConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string stringexpression = BuildExpression(value, parameter.ToString());
            return HtmlPage.Window.Invoke("eval", stringexpression);
        }

        private string BuildExpression(object value, string parameter)
        {
            StringBuilder sb = new StringBuilder(parameter);

            foreach (PropertyInfo propertyInfo in value.GetType().GetProperties())
            {
                if (propertyInfo.CanRead)
                {
                    object o = propertyInfo.GetValue(value, null);
                    sb.Replace(propertyInfo.Name, o.ToString());
                }
            }

            return sb.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
