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

namespace ordersXML
{
	public class CustomerMgrXML : ICustomerMgr
	{
	    DataSet ds = new DataSet();
		string schemaPath = "shared/customers.xsd";
		string xmlPath = "shared/customers.xml";

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

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

		public void RemoveCustomer(string ID)
		{
			DataRow[] rows = ds.Tables[0].Select("ID = '" + ID + "'");
			if (rows.Length == 1)
				rows[0].Delete();
			ds.Tables[0].AcceptChanges();
			ds.WriteXml(xmlPath);
		}

		public ICustomer CreateNew()
		{
			ICustomer customer = new Customer();
			customer.ID = Guid.NewGuid().ToString();
			return customer;
		}
		
		public string AddCustomer(ICustomer customer)
		{
			DataRow newrow = ds.Tables[0].NewRow();
			newrow["ID"] = customer.ID;
			newrow["Name"] = customer.Name;
			ds.Tables[0].Rows.Add(newrow);
			ds.Tables[0].AcceptChanges();
			ds.WriteXml(xmlPath);
			return customer.ID;
		}
		
		public ICustomer this[int Index]
		{
			get
			{
				ICustomer customer = new Customer();
				customer.ID = (string)ds.Tables[0].Rows[Index]["ID"];
				customer.Name = (string)ds.Tables[0].Rows[Index]["Name"];
				return customer;
			}
		}

		public ICustomer this[string ID]
		{
			get
			{
				ICustomer customer = new Customer();
				DataRow[] rows = ds.Tables[0].Select("ID = '" + ID + "'");
				if (rows.Length == 1)
				{
					customer.ID = (string)rows[0]["ID"];
					customer.Name = (string)rows[0]["Name"];
				}
				return customer;
			}
		}

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