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;

namespace Telerik.Windows.Examples.Examples.TreeView
{
	public class ProductsDataSource
	{
		private static ObservableCollection<Products> products;

		public static IEnumerable<Products> GetProducts()
		{
			StreamResourceInfo resourceInfo = Application.GetResourceStream(GetResourceUri(ProductDataSource));
			if (resourceInfo == null)
				return null;

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

			if (products == null)
			{
				products = GetProductsFromDocument(document);
			}

			return products;
		}

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

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

			return resourceUri;
		}

		protected const string ProductDataSource = "Products/Products.xml";

		protected static ObservableCollection<Products> GetProductsFromDocument(XDocument document)
		{
			ObservableCollection<Products> list = new ObservableCollection<Products>();

			foreach (XElement element in document.Descendants("Products"))
			{
				Products product = new Products();
				product.ProductID = element.Element("ProductID").Value;
				product.CategoryID = element.Element("CategoryID").Value;
				product.UnitPrice = element.Element("UnitPrice").Value;
				product.UnitsInStack = element.Element("UnitsInStock").Value;
				product.ProductName = element.Element("ProductName").Value;
				list.Add(product);
			}

			return list;
		}

		public static IEnumerable<Products> GetProductsByCategory(string categoryID)
		{
			StreamResourceInfo resourceInfo = Application.GetResourceStream(GetResourceUri(ProductDataSource));
			if (resourceInfo == null)
				return null;

			XDocument document = XDocument.Load(XmlReader.Create(resourceInfo.Stream));
			ObservableCollection<Products> categorizedProducts = new ObservableCollection<Products>();
			
			products = GetProductsFromDocument(document);
			foreach (Products product in products)
			{
				if (product.CategoryID == categoryID)
				{
					categorizedProducts.Add(product);
				}
			}
	
			return categorizedProducts;
		}

		public static void AddNewOrder(Products product)
		{
			if (product != null)
			{
				products.Add(product);
			}
		}

		public static void DeleteOrder(Products product)
		{
			if (product != null)
			{
				products.Remove(product);
			}
		}
	}
}
