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

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

        string filename;
        List<Produkt> products;

        public IQueryable<Produkt> Produkty { get { return products.AsQueryable(); } }

        public void AddProduct(Produkt 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.Nazwa));
            newElement.Add(new XElement("Description",product.Opis));
            newElement.Add(new XElement("Price",product.Cena));
            parent.Add(newElement);
            xml.Save(filename);

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