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

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;

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

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

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

        /// <summary>
        /// 셀렉트 공통
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private dynamic _ListSelect(IQueryable<FmsDrawingHistory> query) {
            var list = query.Select(x => new {
                x.SiteId,
                x.DrawingId,
                x.HistoryId,
                x.RevisionNo,
                x.FileId,
                CmFile = _storage.ParseFile(x.CmFile),
                x.Description,
                x.UpdatedDate,
                UpdateUserName = x.CmUser.Name,
            });
            return list;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] string drawingId) {

            //수정필요
            var query = _FilterAndSort(req);
            query = query.Where(x => x.SiteId == Util.ToInt(siteId) && x.DrawingId == Util.ToInt(drawingId));
            var list = _ListSelect(query);
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

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

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

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

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

            return query;
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{drawingId}/{historyId}")]
        public IActionResult Get(int siteId, int drawingId, int historyId) {
            var data = _service.Get(siteId, drawingId, historyId);
            if (data.Count() == 0) {
                return NotFound("사이트 정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.SiteId,
                x.DrawingId,
                x.HistoryId,
                x.RevisionNo,
                CmUser = new {
                    x.CmUser.Name,
                },
                CmFile = _storage.ParseFile(x.CmFile),
                x.Description
            });
            return Ok(list.First());
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{drawingId}")]
        public int GetNextRevisionNo(int siteId, int drawingId) {
            int nextRevisionNo = _service.GetRevisionNo(siteId, drawingId);
            return nextRevisionNo;
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] FmsDrawingHistory data) {
            _logger.LogInformation("Create");
            //_logger.LogInformation(data.Dump());

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


        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{siteId}/{drawingId}/{historyId}")]
        public IActionResult Edit(int siteId, int drawingId, int historyId, [FromBody] FmsDrawingHistory data) {
            _logger.LogInformation("Edit");
            _logger.LogInformation("id:" + historyId);
            _logger.LogInformation("siteId:" + siteId);
            //_logger.LogInformation(data.Dump());
            if (historyId != data.HistoryId) {
                return BadRequest("잘못된 접근입니다.");
            }

            if (ModelState.IsValid) {
                data.UpdatedUserId = User.Identity.Name;
                _service.Edit(data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 삭제
        /// </summary>
        // [HttpDelete("{siteId}/{drawingId}/{historyId}")]
        // public IActionResult Delete(int siteId, int id) {
        //     _service.Delete(id, siteId);
        //     return Ok();
        // }
    }
}