using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AMESCoreStudio.WebApi;
using AMESCoreStudio.WebApi.Models.AMES;
using AMESCoreStudio.CommonTools.Result;

namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 組件類別資料維護
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RepairItemsController : ControllerBase
    {
        private readonly AMESContext _context;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public RepairItemsController(AMESContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        // GET: api/RepairItems
        [HttpGet]
        public async Task<ActionResult<IEnumerable<RepairItem>>> GetRepairItem(int page = 0, int limit = 10)
        {
            IQueryable<RepairItem> q = _context.RepairItems;
            if (page > 0)
            {
                q = q.OrderBy(p => p.ItemNo).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.ItemNo);
            }

            var repairItem = await q.ToListAsync();
            return repairItem;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/RepairItems/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<RepairItem>>> GetRepairItem(string id)
        {
            IQueryable<RepairItem> q = _context.RepairItems;
            q = q.Where(p => p.ItemNo.Equals(id));

            var repairItem = await q.ToListAsync();

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

            return repairItem;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="repairItem"></param>
        /// <returns></returns>
        // PUT: api/RepairItems/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<ResultModel<RepairItem>> PutRepairItem(string id, [FromBody] RepairItem repairItem)
        {
            ResultModel<RepairItem> result = new ResultModel<RepairItem>();

            if (id != repairItem.ItemNo)
            {
                result.Success = false;
                result.Msg = "組件類別代碼錯誤";
                return result;
            }

            _context.Entry(repairItem).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RepairItemExists(id))
                {
                    result.Success = false;
                    result.Msg = "組件類別代碼不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

            result.Success = true;
            result.Msg = "OK";
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="repairItem"></param>
        /// <returns></returns>
        // POST: api/RepairItems
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ResultModel<RepairItem>> PostRepairItem([FromBody] RepairItem repairItem)
        {
            ResultModel<RepairItem> result = new ResultModel<RepairItem>();
            _context.RepairItems.Add(repairItem);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (RepairItemExists(repairItem.ItemNo))
                {
                    result.Success = false;
                    result.Msg = "組件類別代碼重複";
                    return result;
                }
                else
                {
                    throw;
                }
            }

            result.Success = true;
            result.Msg = "OK";
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/RepairItems/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<RepairItem>> DeleteRepairItem(string id)
        {
            ResultModel<RepairItem> result = new ResultModel<RepairItem>();
            var repairItem = await _context.RepairItems.FindAsync(id);
            if (repairItem == null)
            {
                result.Success = false;
                result.Msg = "組件類別不存在";
                return result;
            }

            _context.RepairItems.Remove(repairItem);
            await _context.SaveChangesAsync();

            result.Success = true;
            result.Msg = "OK";
            return result;
        }

        private bool RepairItemExists(string id)
        {
            return _context.RepairItems.Any(e => e.ItemNo == id);
        }
    }
}