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 FloorController : Controller {
        private readonly ILogger<FloorController> _logger;
        private readonly FMSContext _context;
        private readonly FloorService _service;

        public FloorController(
            ILogger<FloorController> logger,
            FMSContext context,
            FloorService service
            ) {
            _logger = logger;
            _context = context;
            _service = service;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery]PagingRequest req, [FromQuery] string siteId) {
            var query = _FilterAndSort(req);
            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            var list = query.Select(x => new {
                x.SiteId,
                x.BuildingId,
                x.FloorId,
                CmSite = new {
                    x.CmSite.Name,
                },
                CmBuilding = new {
                    x.CmBuilding.Name,
                },
                x.Name,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string buildingId, [FromQuery] string floorId) {
            var floor = _service.GetAll().Where(x => x.SiteId == Util.ToInt(siteId)
                && x.BuildingId == Util.ToInt(buildingId)
                && x.FloorId == Util.ToInt(floorId)).FirstOrDefault();

            return Ok(new {
                floor.SiteId,
                floor.BuildingId,
                BuildingName = floor.CmBuilding?.Name ?? "",
                floor.FloorId,
                floor.Name,
            });
        }

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

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

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

            return query;
        }

    }
}