using System;
using System.Linq;
using System.Threading.Tasks;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSApp.Services;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;

namespace FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[controller]")]
    public class ManualHistoryController : Controller {
        private readonly ILogger<ManualHistoryController> _logger;
        private readonly FMSContext _context;
        private readonly ManualHistoryService _service;
        private readonly StorageHelper _storage;

        public ManualHistoryController(
            ILogger<ManualHistoryController> logger,
            FMSContext context,
            ManualHistoryService service,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] string ManualId) {
            var query = _FilterAndSort(req);
            query = query.Where(x => x.SiteId == Util.ToInt(siteId) && x.ManualId == Util.ToInt(ManualId));
            var list = query.Select(x => new {
                x.SiteId,
                x.ManualId,
                x.HistoryId,
                x.RevisionNo,
                x.FileId,
                CmFile = _storage.ParseFile(x.CmFile),
                x.Description,
                x.UpdatedDate,
                x.UpdatedUserId,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string ManualId, [FromQuery] string historyId, [FromQuery] string userId, [FromQuery] string isCreate) {
            if (Util.ToBool(isCreate)) {
                var query = _service.GetAll()
                    .Where(x => x.SiteId == Util.ToInt(siteId) && x.ManualId == Util.ToInt(ManualId)).OrderByDescending(x => x.HistoryId);
                var item = query.Select(x => new {
                    x.SiteId,
                    RevisionNo = Util.ToInt(x.RevisionNo) + 1
                }).FirstOrDefault();
                return Ok(item);
            } else {
                var query = _service.GetAll()
                    .Where(x => x.SiteId == Util.ToInt(siteId) && x.ManualId == Util.ToInt(ManualId) && x.HistoryId == Util.ToInt(historyId));
                var item = query.Select(x => new {
                    x.SiteId,
                    x.ManualId,
                    x.HistoryId,
                    x.RevisionNo,
                    CmFile = _storage.ParseFile(x.CmFile),
                    x.Description,
                    x.UpdatedDate,
                    x.UpdatedUserId,
                    CmUser = new {
                        Name = x.CmUser.Name
                    }
                }).FirstOrDefault();
                return Ok(item);
            }
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsManualHistory data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        [HttpDelete("{siteId}/{manualId}/{historyId}")]
        public IActionResult Delete(int siteId, int manualId, int historyId) {
            _service.Delete(siteId, manualId, historyId);
            return Ok();
        }

        // 검색 & 정렬 공통
        private IQueryable<FmsManualHistory> _FilterAndSort(PagingRequest req) {
            var query = _service.GetAll();

            // 기본 Entity 검색
            query = query.Filter(req.conditions);

            // 기본 Entity 정렬
            query = query.Sort(req.sort);

            return query;
        }

    }
}