using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers {
  public class ExempleAttachementController : Controller {
    private NorthwindEntities DC = new NorthwindEntities();

    public ActionResult Index() {
      var products = DC.Products.OrderBy( p => p.UnitPrice ).Select( p => new ProductPourListeViewModel() { ProductID = p.ProductID, CategoryName = p.Category.CategoryName, ProductName = p.ProductName, UnitPrice = p.UnitPrice } );
      return View( "Index", products );
    }

    public ActionResult Supprimer( Product victime ) {
      if( Request.HttpMethod == "GET" || victime.ProductID == 0 )
        return Index();
			victime.UnitPrice = 1234.01m;
      DC.Entry<Product>( victime ).State = System.Data.Entity.EntityState.Deleted;
      try {
        DC.SaveChanges();
        ViewBag.Message = $"Confirmation : le produit N°{victime.ProductID} à {victime.UnitPrice:0.00}$ est supprimé";
        return Index();
      }
      catch( DbUpdateConcurrencyException cac ) {
        var erreur = cac.Entries.Single();
        var nvValeurs = erreur.GetDatabaseValues();
        ViewBag.Message = string.Format(
          "Le prix du produit '{0}' a changé ({1} => {2}). Suppression abandonnée.",
          nvValeurs["ProductName"], victime.UnitPrice, nvValeurs["UnitPrice"] );
        DC.Entry( victime ).State = System.Data.Entity.EntityState.Detached;
        return Index();
      }
    }

    protected override void Dispose( bool disposing ) {
      if( disposing )
				DC.Dispose();
      base.Dispose( disposing );
    }
  }
}