using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
using System.Web.Mvc;

namespace BLL
{
    public class Products
    {
        DataClassesDataContext _db = new DataClassesDataContext();

        public PagedList<Product> AllPaged(int? pageIndex, bool cached)
        {
            if (cached)
            {
                ICacheManager cache = CacheFactory.GetCacheManager();
                PagedList<Product> _Product = (PagedList<Product>)cache["Product" + pageIndex.ToString()];
                if (_Product == null)
                {
                    _Product = _db.Product.OrderByDescending(p => p.PID).ToPagedList(pageIndex);
                    cache.Add("Product" + pageIndex.ToString(), _Product);
                }
                return _Product;
            }
            else
            {
                PagedList<Product> _Product =  _db.Product.OrderByDescending(p => p.PID).ToPagedList(pageIndex);
                return _Product;
            }
        }

        public Product Get(int id)
        {
            var _Product = _db.Product.Single(p => p.PID.Equals(id));
            return _Product;
        }

        public int Insert(Product _Product)
        {
            _db.Product.InsertOnSubmit(_Product);
            _db.SubmitChanges();
            return _Product.PID;
        }

        public void Update(int id, Product _Product)
        {
            var item = _db.Product.Single(p => p.PID.Equals(id));
            item.ProductName = _Product.ProductName;
            _db.SubmitChanges();
        }

        public void Delete(int id)
        {
            var item = _db.Product.Single(p => p.PID.Equals(id));
            _db.Product.DeleteOnSubmit(item);
            _db.SubmitChanges();
        }
    }
}
