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

namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WipLogController : Controller
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 工單投產纪錄資料文件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<WipLog>>> GetWipLog()
        {
            IQueryable<WipLog> q = _context.WipLogs;
            q = q.OrderBy(p => p.WipID);
            var WipLog = await q.ToListAsync();
            return WipLog;
        }

        /// <summary>
        /// 工單投產纪錄資料文件 to WipID
        /// </summary>
        /// <param name="id">工單ID</param>
        /// <returns></returns>
        // GET: api/RolePrograms/5
        [HttpGet("{id}")]
        public async Task<ActionResult<WipLog>> GetWipLog(int id)
        {
            IQueryable<WipLog> q = _context.WipLogs;

            var WipLog = await q.Where(p => p.WipID == id).OrderByDescending(o => o.CreateDate).FirstOrDefaultAsync();

            //if (WipLog == null)
            //{
            //    return NotFound();
            //}

            return WipLog;
        }

        /// <summary>
        /// 新增工單投產纪錄資料文件
        /// </summary>
        /// <param name="wipLog">工單ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PostWipLog([FromBody]WipLog wipLog)
        {
            //Helper helper = new Helper(_context);
            //wipLog.WipID = wipLog.WipID == 0 ? helper.GetIDKeyNoPost("WIP_ID").Result : wipLog.WipID;
            _context.WipLogs.Add(wipLog);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch
            {

            }
            return Ok();
            //return ;
        }
    }
}