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 SiteController : Controller {
        private readonly ILogger<SiteController> _logger;
        private readonly FMSContext _context;
        private readonly SiteService _service;
        private readonly StorageHelper _storage;

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

        /// <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.Name,
                x.AddressZip1,
                x.Address1,
                x.Adderss2,
                x.PhoneNo,
                x.IsUse,
                x.IsControlSchedule,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId) {
            var site = _service.GetAll().Where(x => x.SiteId == Util.ToInt(siteId)).FirstOrDefault();

            return Ok(new {
                site.SiteId,
                site.Name,
                site.AddressZip1,
                site.Address1,
                site.Adderss2,
                site.PhoneNo,
                site.IsUse,
                site.CompletionDate, //준공연도
                site.BuildingSize, //건축규모
                site.GrossArea, // 연면적
                site.BuildingArea,  // 건축면적
                site.FloorAreaRatio,    // 용적율
                site.BuildingCoverageRatio, // 건폐율
                site.MainUse,   // 주용도
                site.IsControlSchedule, // 제어스케줄
                site.ScheduleCheckHour, // 스케줄알람시간
                site.Hdd,   // 기준온도 HDD
                site.Cdd,   // 기준온도 CDD
                site.Standard, // 용도별표준값
                site.Url,   // 홈페이지
                site.Comment, // 비고
                ImageFile = _storage.ParseFile(site.ImageFile)
            });
        }

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

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

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

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

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

            return query;
        }

    }
}