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

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

    public ActionResult Index( string tri ) {
      var products = DC.Products.Include( p => p.Category ).AsQueryable(); // Comme ça j'ai un IQueryable<Product>, pas un DbSet<Product>
      switch( tri ) {
        case "nom_desc":
          products = products.OrderByDescending( p => p.ProductName );
          break;
        case "prix_asc":
          products = products.OrderBy( p => p.UnitPrice );
          break;
        case "prix_desc":
          products = products.OrderByDescending( p => p.UnitPrice );
          break;
        default:
          products = products.OrderBy( p => p.ProductName );
          tri = "nom_asc";
          break;
      }
      ViewBag.Tri = tri;
      var viewModel = products.Select( p => new ProductPourListeViewModel() { ProductID = p.ProductID, CategoryName = p.Category.CategoryName, ProductName = p.ProductName, UnitPrice = p.UnitPrice } );
      return View( "Index", viewModel );
    }

    public ActionResult Supprimer( Product victime, string tri ) {
      if( Request.HttpMethod == "GET" || victime.ProductID == 0 )
        return Index( tri );
      victime.UnitPrice = 1234.01m;
      DC.Entry<Product>( victime ).State = System.Data.Entity.EntityState.Deleted;
      try {
        DC.SaveChanges();
        ViewBag.Message = String.Format("Confirmation : le produit N°{0} à {1:0.00}$ est supprimé", victime.ProductID, victime.UnitPrice );
        return Index( tri );
      }
      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( tri );
      }
    }

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