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 RepairRecordsController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        // GET: api/RepairRecords
        [HttpGet]
        public async Task<ActionResult<IEnumerable<RepairRecord>>> GetRepairRecord()
        {
            return await _context.RepairRecords.ToListAsync();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/RepairRecords/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<RepairRecord>>> GetRepairRecord(int id)
        {
            IQueryable<RepairRecord> q = _context.RepairRecords;
            q = q.Where(p => p.ComponentID.Equals(id));

            var repairRecord = await q.ToListAsync();

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

            return repairRecord;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/RepairRecords/5
        [HttpGet("NG_ID/{id}")]
        public async Task<ActionResult<IEnumerable<RepairRecord>>> GetRepairRecordByNgID(int id)
        {
            IQueryable<RepairRecord> q = _context.RepairRecords;
            q = q.Where(p => p.NgID.Equals(id));

            var repairRecord = await q.ToListAsync();

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

            return repairRecord;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="repairRecord"></param>
        /// <returns></returns>
        // PUT: api/RepairRecords/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<RepairRecord>> PutRepairRecord(int id, RepairRecord repairRecord)
        {
            ResultModel<RepairRecord> result = new ResultModel<RepairRecord>();
            if (id != repairRecord.ComponentID)
            {
                result.Success = false;
                result.Msg = "不良零件ID錯誤";
                return result;
            }

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

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RepairRecordExists(id))
                {
                    result.Success = false;
                    result.Msg = "不良零件ID不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="repairRecord"></param>
        /// <returns></returns>
        // POST: api/RepairRecords
        // 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<RepairRecord>> PostRepairRecord(RepairRecord repairRecord)
        {
            ResultModel<RepairRecord> result = new ResultModel<RepairRecord>();

            var data = await _context.RepairRecords.FindAsync(repairRecord.ComponentID);
            if (data != null)
            {
                _context.RepairRecords.Remove(data);

                await _context.SaveChangesAsync();
            }

            _context.RepairRecords.Add(repairRecord);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (RepairRecordExists(repairRecord.ComponentID))
                {
                    result.Success = false;
                    result.Msg = "不良零件ID重複";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/RepairRecords/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<RepairRecord>> DeleteRepairRecord(decimal id)
        {
            ResultModel<RepairRecord> result = new ResultModel<RepairRecord>();
            var repairRecord = await _context.RepairRecords.FindAsync(id);
            if (repairRecord == null)
            {
                result.Success = false;
                result.Msg = "不良零件ID不存在";
                return result;
            }

            _context.RepairRecords.Remove(repairRecord);
            await _context.SaveChangesAsync();

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

        private bool RepairRecordExists(decimal id)
        {
            return _context.RepairRecords.Any(e => e.ComponentID == id);
        }
    }
}