using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebApplication1.Models;

namespace WebApplication1.Controllers {
  public class ExempleProductsWebApiController : ApiController {
    private NorthwindEntities DC = new NorthwindEntities();
    public IQueryable<object> GetProducts() { // Convention : préfixer par le verbe HTTP
      return DC.Products.Select( p => new { p.ProductID, p.ProductName } );
    }
		public IHttpActionResult GetProduct( int id ) {
      var productVM = DC.Products.Select( p => new { p.ProductID, p.ProductName, p.Category.CategoryName, p.Category.Description, p.UnitPrice, p.UnitsInStock } ).FirstOrDefault( p => p.ProductID == id );
      if( productVM == null )
        return NotFound();
      return Ok( productVM );
    }
    public IHttpActionResult PutProduct( int id, Product product ) {
      if( !ModelState.IsValid || id != product.ProductID )
        return BadRequest( ModelState );
      DC.Entry( product ).State = EntityState.Modified;
      try {
        DC.SaveChanges();
      }
      catch( DbUpdateConcurrencyException ) {
        if( DC.Products.Any( p => p.ProductID == id ) )
          throw;
        return NotFound();
      }
      return StatusCode( HttpStatusCode.NoContent );
    }
    public IHttpActionResult PostProduct( Product product ) {
      if( !ModelState.IsValid )
        return BadRequest( ModelState );
			product.CategoryID = 1;
      DC.Products.Add( product );
      DC.SaveChanges();
      return CreatedAtRoute( "DefaultApi", new { id = product.ProductID }, product ); // URI vers la ressource créée ("DefaultApi" est le nom de la route)
    }
    public IHttpActionResult DeleteProduct( int id ) {
      DC.Entry( new Product() { ProductID = id } ).State = EntityState.Deleted;
      if( DC.SaveChanges() != 1 )
        return NotFound();
      return Ok( id );
    }
    protected override void Dispose( bool disposing ) {
      if( disposing )
        DC.Dispose();
      base.Dispose( disposing );
    }
  }
}