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

namespace ordersXML
{
	public class InventoryMgrXML : IInventoryMgr
	{
		DataSet ds = new DataSet();
		string schemaPath = "shared/inventory.xsd";
		string xmlPath = "shared/inventory.xml";

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

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

		public IInventory this[int Index]
		{
			get
			{
				IInventory item = new Inventory();
				item.ID = (string)ds.Tables[0].Rows[Index]["ID"];
				item.Description  = (string)ds.Tables[0].Rows[Index]["Description"];
				item.Qty = System.Convert.ToInt32(ds.Tables[0].Rows[Index]["Qty"]);
				return item;
			}
		}

		public IInventory this[string ID]
		{
			get
			{
				IInventory item = new Inventory();
				DataRow[] rows = ds.Tables[0].Select("ID = '" + ID + "'");
				if (rows.Length == 1)
				{
					item.ID = (string)rows[0]["ID"];
					item.Description  = (string)rows[0]["Description"];
					item.Qty = (int)System.Convert.ToInt32(rows[0]["Qty"]);
				}
				return item;
			}
		}

		public int Count
		{
			get
			{
				return ds.Tables[0].Rows.Count;
			}
		}

		public void UpdateInventory(IInventory item)
		{
			DataRow[] rows = ds.Tables[0].Select("ID = '" + item.ID + "'");
			if (rows.Length == 1)
			{
				rows[0]["ID"] = item.ID;
				rows[0]["Description"] = item.Description;
				rows[0]["Qty"] = item.Qty;
				ds.Tables[0].AcceptChanges();
				ds.WriteXml(xmlPath);
			}		
		}

	}
}
