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.Resources;
using System.Xml.Linq;
using System.Xml;
using System.Reflection;
using System.Collections.ObjectModel;
using Telerik.Windows.Examples;
using System.Collections.Generic;
using System.Globalization;

namespace Telerik.Windows.Examples.Examples.TreeView
{
	public class OrderDetailsDataSource
	{
		private static ObservableCollection<OrderDetails> orders;

		public static IEnumerable<OrderDetails> GetOrderDetails()
		{
			StreamResourceInfo resourceInfo = Application.GetResourceStream(GetResourceUri(OrderDetailDataSource));
			if (resourceInfo == null)
				return null;

			XDocument document = XDocument.Load(XmlReader.Create(resourceInfo.Stream));

			if (orders == null)
			{
				orders = GetOrderDetailsFromDocument(document);
			}

			return orders;
		}

		public static IEnumerable<OrderDetails> GetOrderDetailsByProduct(string productID)
		{
			StreamResourceInfo resourceInfo = Application.GetResourceStream(GetResourceUri(OrderDetailDataSource));
			if (resourceInfo == null)
				return null;

			XDocument document = XDocument.Load(XmlReader.Create(resourceInfo.Stream));
			ObservableCollection<OrderDetails> categorizedProducts = new ObservableCollection<OrderDetails>();

			orders = GetOrderDetailsFromDocument(document);
			foreach (OrderDetails order in orders)
			{
				if (order.ProductID == productID)
				{
					categorizedProducts.Add(order);
				}
			}
			return categorizedProducts;
		}

		internal static Uri GetResourceUri(string resource)
		{
			AssemblyName assemblyName = new AssemblyName(typeof(OrderDetailsDataSource).Assembly.FullName);
			string resourcePath = "/" + assemblyName.Name + ";component/" + resource;

			Uri resourceUri = new Uri(resourcePath, UriKind.Relative);

			return resourceUri;
		}

		protected const string OrderDetailDataSource = "OrderDetails/OrderDetails.xml";

		protected static ObservableCollection<OrderDetails> GetOrderDetailsFromDocument(XDocument document)
		{
			ObservableCollection<OrderDetails> list = new ObservableCollection<OrderDetails>();

			foreach (XElement element in document.Descendants("Order_Details"))
			{
				OrderDetails order = new OrderDetails();

				order.Discount = element.Element("Discount").Value;
				order.OrderID = element.Element("OrderID").Value;
				order.ProductID = element.Element("ProductID").Value;
				order.Quantity = element.Element("Quantity").Value;
				order.UnitPrice = element.Element("UnitPrice").Value;

				list.Add(order);
			}

			return list;
		}
	}
}
