using MvcAvecTests.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAvecTests.Controllers {
	public class ECommerceController : Controller {
		public ActionResult Index() {
			return View( "Index", Article.Stock.Values.ToList() );
		}
		[HttpGet, ActionName( "Ajouter" )]
		public ActionResult AjouterGet() {
			return RedirectToAction( "Index" );
		}
		[HttpPost]
		public ActionResult Ajouter( int id, int nb ) {
			System.Web.HttpContext.Current.Cache["bb"] = 123;
			HttpContext.Cache["aa"] = 12;
			Article articleDuCaddie;
			Article enStock = Article.Stock[id];
			if( Article.Caddie.TryGetValue( id, out articleDuCaddie ) ) {
				if( (articleDuCaddie.Quantite += nb) < 1 )
					Article.Caddie.Remove( id );
				else if( articleDuCaddie.Quantite > enStock.Quantite ) {
					articleDuCaddie.Quantite -= nb;
					ViewBag.Erreur = "Pas assez de stock !";
					return Index();
				}
			}
			else if( nb > 0 ) {
				if( enStock.Quantite < nb ) {
					ViewBag.Erreur = "Pas assez de stock !";
					return Index();
				}
				Article.Caddie.Add( id, new Article( id, enStock.Nom, enStock.Prix, nb ) );
			}
			return RedirectToAction( "Index", "Caddie" );
		}
	}
}