using System;
using System.Linq;
using System.Collections.Generic;
using Telerik.Windows.Data;
using Telerik.Windows.Controls.GridView;

namespace SilverlightApplication1
{
    public static class DescriptorsExtensions
    {
        public static string ToDynamicLinq(this SortDescriptorCollection source)
        {
            var result = new List<string>();

            foreach (var d in source)
            {
                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.ToDynamicLinq()).ToArray());
		}

        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());
        }
    }
}
