﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using Composite.Data;

namespace WebApiDemo
{
    public class ProductController : ApiController
    {
        // Getting the list of products
        public IEnumerable<Product> Get()
        {
            using (var c = new DataConnection())
            {
                return c.Get<Product>().OrderBy(p => p.Title).ToList();
            }
        }

        // Getting a product by id
        public Product Get(Guid id)
        {
            using (var c = new DataConnection())
            {
                return c.Get<Product>().FirstOrDefault(p => p.Id == id);
            }
        }

        // Adding a new product
        public Product PostProduct(Product product)
        {
            using (var c = new DataConnection())
            {
                product.Id = Guid.NewGuid();

                return c.Add(product);
            }
        }

        // Updating an existing Product
        public void PutProduct(Guid id, Product productJson)
        {
            using (var c = new DataConnection())
            {
                var product = c.Get<Product>().FirstOrDefault(p => p.Id == id);
                if (product == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                product.Title = productJson.Title;
                product.Price = productJson.Price;

                c.Update(product);
            }
        }

        // Deleting a new product
        public void DeleteProduct(Guid id)
        {
            using (var c = new DataConnection())
            {
                var product = c.Get<Product>().FirstOrDefault(p => p.Id == id);

                if (product != null)
                {
                    c.Delete(product);
                }
            }
        }
    }
}
