using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using test.Models.Entities;
using test.Models.Abstract;
using System.Xml;

namespace test.Models.Concrete
{
    public class XMLProductRepository : IProductRepository
    {
        public XMLProductRepository(string xmlfilename)
        {
            filename = xmlfilename;
            products = new List<Product>();
            XDocument xml = XDocument.Load(xmlfilename);
            var list = xml.Descendants("Product");
            foreach (var product in list)
            {
                products.Add(new Product()
                {
                    Id = int.Parse(product.Attribute("id").Value),
                    Name = product.Element("Name").Value,
                    Description = product.Element("Description").Value,
                    Price = decimal.Parse(product.Element("Price").Value.Replace(".",","))
                });
            }
        }

        string filename;
        List<Product> products;

        public IQueryable<Product> Products { get { return products.AsQueryable(); } }

        public void AddProduct(Product product)
        {
            // write in xml
            XDocument xml=XDocument.Load(filename);
            XElement parent = xml.Element("products");
            XElement newElement=new XElement("Product");
            newElement.Add(new XAttribute("id",products.Max(x=>x.Id)+1));
            newElement.Add(new XElement("Name", product.Name));
            newElement.Add(new XElement("Description",product.Description));
            newElement.Add(new XElement("Price",product.Price));
            parent.Add(newElement);
            xml.Save(filename);

            // add to actual repository
            products.Add(product);
        }
    }
}