using System;
using System.Net;
using System.Linq;
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.Collections.Generic;
using Telerik.Windows.Data;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Controls;

namespace SilverlightApplication1
{
	public static class WpfBrowserApplication1
    {
        public static string ToDynamicLinq(this SortDescriptorCollection source)
        {
            var result = new List<string>();
			var sourceSortDescriptors = source.OfType<SortDescriptor>();
			var sourceColumnSortDescriptors = source.OfType<ColumnSortDescriptor>();

			foreach (SortDescriptor d in sourceSortDescriptors)
			{
				result.Add(d.ToDynamicLinq());
			}

			foreach (ColumnSortDescriptor d in sourceColumnSortDescriptors)
            {
                result.Add(d.ToDynamicLinq());
            }

            return String.Join(",", result.ToArray());
        }

        public static string ToDynamicLinq(this FilterDescriptorCollection source)
        {
            var result = new List<string>();

            foreach (var d in source.OfType<ColumnFilterDescriptor>())
            {
                result.Add(d.ToDynamicLinq());
            }

            return String.Join(" && ", result.ToArray());
        }

        public static string ToDynamicLinq(this GroupDescriptorCollection source)
        {
            return String.Join(",", source.OfType<GroupDescriptor>().Select(d=>d.Member).ToArray());
        }

		public static string ToDynamicLinq(this ColumnSortDescriptor source)
        {
            return String.Format("{0} {1}", ((GridViewDataColumn)source.Column).DataMemberBinding.Path.Path, 
                source.SortDirection == System.ComponentModel.ListSortDirection.Ascending ? "asc" : "desc");
        }

		public static string ToDynamicLinq(this SortDescriptor source)
		{
			return String.Format("{0} {1}", source.Member,
				source.SortDirection == System.ComponentModel.ListSortDirection.Ascending ? "asc" : "desc");
		}

        public static string ToDynamicLinq(this GroupDescriptor source)
        {
            return String.Format("{0} {1}", source.Member,
                source.SortDirection == System.ComponentModel.ListSortDirection.Ascending ? "asc" : "desc");
        }

        public static string ToDynamicLinq(this ColumnFilterDescriptor source)
        {
            var result = new List<string>();

            foreach (var item in source.DistinctFilter.DistinctValues)
            { 
                result.Add(String.Format("{0} == {1}", source.DistinctFilter.Member, item.GetType() == typeof(string) ? 
                    String.Format(@"""{0}""", item) : item));
            }

            return String.Join(" || ", result.ToArray());
        }
    }
}
