﻿// Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License.

namespace Zahasoft.Store.Controllers
{
    using Context;
    using Models;
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Web.Http;
    using System.Web.Http.Description;

    public class CommoditiesController : ApiController
    {
        readonly StoreEfContext db = new StoreEfContext();

        // GET: api/commodities
        public IQueryable<Commodity> GetCommodities() => db.Commodities;

        // PUT: api/commodities/{id}
        [ResponseType(typeof(Commodity))]
        public IHttpActionResult PutCommodity(string id, CommodityViewModel model)
        {
            if (!ModelState.IsValid || model.Quantity <= 0)
            {
                return BadRequest(ModelState);
            }

            Commodity commodity = db.Commodities.Find(model.Name);

            if (commodity != null)
            {
                if (model.Action == ActionType.Add)
                {
                    commodity.Quantity = commodity.Quantity + model.Quantity;
                }

                if (model.Action == ActionType.Remove)
                {
                    if (commodity.Quantity - model.Quantity < 0)
                    {
                        return BadRequest(ModelState);
                    }

                    commodity.Quantity = commodity.Quantity - model.Quantity;
                }
            }

            db.Entry(commodity).State = EntityState.Modified;

            db.Histories.Add(new History
            {
                Id = Guid.NewGuid().ToString(),
                Date = DateTime.Now,
                Action = model.Action,
                Quantity = model.Quantity,
                Commodity = model.Name
            });

            try
            {
                db.SaveChanges();
            }
            catch (Exception)
            {
                return NotFound();
            }

            return Ok(commodity);
        }

        // GET: api/commodities/{id}
        [ResponseType(typeof(Commodity))]
        public IHttpActionResult GetCommodity(string id)
        {
            Commodity commodity = db.Commodities.Find(id);

            if (commodity == null)
            {
                return NotFound();
            }

            return Ok(commodity);
        }

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

        bool CommodityExists(string id) => db.Commodities.Count(e => e.Name == id) > 0;
    }
}