using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication1.Models;

namespace WebApplication1.Repositories.ArticleCommerceRepository {
  public class ArticleCommerceRepositoryMemoire : ArticleCommerceRepositoryBase {
    private static readonly Dictionary<Guid, Article> Stock = Article.Stock;
    private static Dictionary<Guid, ArticleCommerce> Caddie {
      get {
        var caddie = (Dictionary<Guid, ArticleCommerce>)HttpContext.Current.Session["Caddie"];
        if( caddie == null )
          HttpContext.Current.Session["Caddie"] = caddie = new Dictionary<Guid, ArticleCommerce>();
        return caddie;
      }
    }
    public override ArticleCommerce AjouterAuCaddie( Guid articleCommerceId ) {
      ArticleCommerce ac;
      if( Caddie.TryGetValue( articleCommerceId, out ac ) ) {
        ac.Quantite++;
      }
      else {
        var articleEnStock = Article.Stock[articleCommerceId];
        ac = new ArticleCommerce( articleEnStock.Id, articleEnStock.PrixVente, 1, articleEnStock.Nom );
        Caddie.Add( ac.Id, ac );
      }
      return ac;
    }
    public override void ViderCaddie() {
      Caddie.Clear();
    }
    public override IList<ArticleCommerce> ListerCaddie() {
      return Caddie.Values.ToList();
    }
    public override IList<ArticleCommerce> ListerStock() {
      lock( Stock ) {
        return Stock.Values.Select( a => new ArticleCommerce( a.Id, a.PrixAchat, a.Quantite, a.Nom ) ).ToList();
      }
    }
  }
}
