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

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

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

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

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

            var kpLink = await q.ToListAsync();

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

            return kpLink;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="kPLink"></param>
        /// <returns></returns>
        // PUT: api/KPLinks/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<KPLink>> PutKPLink(string id, [FromBody]KPLink kPLink)
        {
            ResultModel<KPLink> result = new ResultModel<KPLink>();

            if (id != kPLink.KeyPartSn)
            {
                result.Success = false;
                result.Msg = "序號錯誤";
                return result;
            }

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

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!KPLinkExists(id))
                {
                    result.Success = false;
                    result.Msg = "序號不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="kPLink"></param>
        /// <returns></returns>
        // POST: api/KPLinks
        // 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<KPLink>> PostKPLink([FromBody]KPLink kPLink)
        {
            ResultModel<KPLink> result = new ResultModel<KPLink>();
            _context.KPLinks.Add(kPLink);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (KPLinkExists(kPLink.KeyPartSn))
                {
                    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/KPLinks/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<KPLink>> DeleteKPLink(string id)
        {
            ResultModel<KPLink> result = new ResultModel<KPLink>();

            var kPLink = await _context.KPLinks.FindAsync(id);
            if (kPLink == null)
            {
                result.Success = false;
                result.Msg = "序號不存在";
                return result;
            }

            _context.KPLinks.Remove(kPLink);
            await _context.SaveChangesAsync();

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

        private bool KPLinkExists(string id)
        {
            return _context.KPLinks.Any(e => e.KeyPartSn == id);
        }
    }
}