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.BAS;

namespace AMESCoreStudio.WebApi.Controllers.BAS
{
    /// <summary>
    /// 流程站別資料維護
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RuleStationsController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 獲取全部流程站別資料
        /// </summary>
        /// <returns></returns>
        // GET: api/RuleStations
        [HttpGet]
        public async Task<ActionResult<IEnumerable<RuleStation>>> GetRuleStation()
        {
            IQueryable<RuleStation> q = _context.RuleStations;

            q = q.OrderBy(p => p.FlowRuleID + p.Sequence);

            var ruleStation = await q.ToListAsync();

            foreach (var data in ruleStation)
            {
                data.Station = _context.Stationses.Where(p1 => p1.StationID.Equals(data.StationID)).FirstOrDefault();
            }

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

            return ruleStation;
        }

        /// <summary>
        /// 根據流程ID獲取該流程站別資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        // GET: api/RuleStations/Flow/5
        [HttpGet("Flow/{id}")]
        public async Task<ActionResult<IEnumerable<RuleStation>>> GetRuleStationByFlow(int id, int page = 1, int limit = 10)
        {
            IQueryable<RuleStation> q = _context.RuleStations;

            if (id > 0)
            {
                q = q.Where(p => p.FlowRuleID.Equals(id));
            }
            if (page > 0)
            {
                q = q.OrderBy(p => p.Sequence).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.Sequence);
            }

            try
            {
                var ruleStation = await q.ToListAsync();

                foreach (var data in ruleStation)
                {
                    data.Station = _context.Stationses.Where(p1 => p1.StationID.Equals(data.StationID)).FirstOrDefault();
                }

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

                return ruleStation;
            }
            catch (Exception e1)
            {
                string msg = e1.Message;
            }

            return NotFound();

            
        }

        /// <summary>
        /// 根據流程站別ID獲取指定單一資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/RuleStations/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<RuleStation>>> GetRuleStation(int id)
        {
            IQueryable<RuleStation> q = _context.RuleStations;

            q = q.Where(p => p.RuleStationID.Equals(id));

            var ruleStation = await q.ToListAsync();

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

            return ruleStation;
        }

        /// <summary>
        /// 更新流程站別資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="ruleStation"></param>
        /// <returns></returns>
        // PUT: api/RuleStations/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<ActionResult<RuleStation>> PutRuleStation(int id, [FromBody] RuleStation ruleStation)
        {
            if (id != ruleStation.RuleStationID)
            {
                return BadRequest();
            }

            _context.Entry(ruleStation).State = EntityState.Modified;
            ruleStation.UpdateDate = DateTime.Now;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RuleStationExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return ruleStation;
        }

        /// <summary>
        /// 新增流程站別資料
        /// </summary>
        /// <param name="ruleStation"></param>
        /// <returns></returns>
        // POST: api/RuleStations
        // 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<ActionResult<RuleStation>> PostRuleStation([FromBody] RuleStation ruleStation)
        {
            Helper helper = new Helper(_context);
            ruleStation.RuleStationID = helper.GetIDKey("RULE_STATION_ID").Result;
            ruleStation.CreateDate = DateTime.Now;

            _context.RuleStations.Add(ruleStation);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetRuleStation", new { id = ruleStation.RuleStationID }, ruleStation);
        }

        /// <summary>
        /// 刪除流程站別資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/RuleStations/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<RuleStation>> DeleteRuleStation(int id)
        {
            var ruleStation = await _context.RuleStations.FindAsync(id);
            if (ruleStation == null)
            {
                return NotFound();
            }

            _context.RuleStations.Remove(ruleStation);
            await _context.SaveChangesAsync();

            return ruleStation;
        }

        private bool RuleStationExists(int id)
        {
            return _context.RuleStations.Any(e => e.RuleStationID == id);
        }
    }
}