using System;
using ordersInterfaces;
using System.Xml;
using System.Web;
using System.Data;

namespace ordersXML
{
	public class OrderMgrXML : IOrderMgr
	{
		DataSet ds = new DataSet();
		string schemaPath = "shared/orders.xsd";
		string xmlPath = "shared/orders.xml";

		public OrderMgrXML()
		{
			if (HttpContext.Current != null)
			{
				schemaPath = HttpContext.Current.Server.MapPath("shared/orders.xsd");
				xmlPath = HttpContext.Current.Server.MapPath("shared/orders.xml");
			}

			if (System.IO.File.Exists(schemaPath))
				ds.ReadXmlSchema(schemaPath);
            
			if (System.IO.File.Exists(xmlPath))
				ds.ReadXml(xmlPath);
		}

		public int Count(string customerID)
		{
			DataRow[] rows = ds.Tables[0].Select("CustomerID='" + customerID + "'");
			return rows.Length;
		}

		public void EnterOrder(ICustomer customer, IInventory item, int qty)
		{
			DataRow[] rows = ds.Tables[0].Select("CustomerID='" + customer.ID + "' and InventoryID='" + item.ID +"'");
			if (rows.Length == 1 )
			{
				rows[0]["Qty"] = System.Convert.ToInt32(rows[0]["Qty"]) + qty;
			}
			else
			{
				DataRow newrow = ds.Tables[0].NewRow();
				newrow["CustomerID"] = customer.ID;
				newrow["InventoryID"] = item.ID;
				newrow["Description"] = item.Description;
				newrow["Qty"] = qty;
				ds.Tables[0].Rows.Add(newrow);
			}
			
			ds.Tables[0].AcceptChanges();
			ds.WriteXml(xmlPath);
		}

		public IOrderItem this[string customerID, int Index]
		{
			get
			{
				DataRow[] rows = ds.Tables[0].Select("customerID='" + customerID + "'");
				if (rows.Length  > 0)
				{
					IOrderItem item = new OrderItem();
					item.CustomerID = (string)rows[Index]["CustomerID"];
					item.InventoryID = (string)rows[Index]["InventoryID"];
					item.Description = (string)rows[Index]["Description"];
					item.Qty = System.Convert.ToInt32(rows[Index]["Qty"]);
					return item;
				}
				
				return null;
			}
		}

	}
}
