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;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;

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

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

        [HttpGet("[action]")]
        public IActionResult DefaultDashboardList() {
            return Ok(List(null, ShortcutType.대시보드메뉴, false));
        }

        [HttpGet("[action]")]
        public IActionResult DefaultBottomList() {
            return Ok(List(null, ShortcutType.하단메뉴, false));
        }

        [HttpGet("[action]")]
        public IActionResult DashboardList([FromQuery] string userId) {
            var list = List(userId, ShortcutType.대시보드메뉴);
            if (list.Count() == 0) {
                return DefaultDashboardList();
            } else {
                return Ok(RemoveDeleted(list));
            }
        }

        [HttpGet("[action]")]
        public IActionResult BottomList([FromQuery] string userId) {
            var list = List(userId, ShortcutType.하단메뉴);
            _logger.LogInformation($"BottomList - list.Count = {list.Count()}");
            if (list.Count() == 0) {
                return DefaultBottomList();
            } else {
                return Ok(RemoveDeleted(list));
            }
        }

        private IQueryable<object> RemoveDeleted(IQueryable<object> list) {
            return list.Where("IsDelete == false");
        }

        private IQueryable<object> List(string userId, ShortcutType type, bool useDeleted = true) {
            var query = _service.GetAll();

            query = query.Where(x => x.Type == type);
            if (string.IsNullOrEmpty(userId)) {
                query = query.Where(x => x.UserId == null || x.UserId == "");
            } else {
                query = query.Where(x => x.UserId == userId);
            }
            if (!useDeleted) {
                query = query.Where(x => x.IsDelete == false);
            }

            query = query.OrderBy(x => x.Position);

            var list = query.Select(x => new {
                x.MobileShortcutId,
                x.UserId,
                UserName = x.CmUser.Name,
                x.SitemapId,
                Sitemap = new {
                    x.Sitemap.Name,
                    x.Sitemap.Path,
                },
                x.Type,
                x.Icon,
                x.IsDelete,
            });
            return list;
        }

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

            return Ok(new {
                shortcut.MobileShortcutId,
                UserId = shortcut.UserId ?? "",
                UserName = shortcut.CmUser?.Name ?? "",
                shortcut.SitemapId,
                Sitemap = new {
                    shortcut.Sitemap.Name,
                    shortcut.Sitemap.Path,
                },
                shortcut.Type,
                shortcut.Icon,
            });
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] MobileShortcut data) {
            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        [HttpDelete("{userId}/{sitemapId}/{type}")]
        public IActionResult DeleteBottom(string userId, int sitemapId, ShortcutType type) {
            _service.Delete(userId, sitemapId, type);
            return Ok();
        }

        [HttpGet("[action]")]
        public IActionResult PositionUp([FromQuery] string userId, [FromQuery] int sitemapId, [FromQuery] ShortcutType type) {
            _service.PositionUp(userId, sitemapId, type);
            return Ok();
        }

        [HttpGet("[action]")]
        public IActionResult PositionDown([FromQuery] string userId, [FromQuery] int sitemapId, [FromQuery] ShortcutType type) {
            _service.PositionDown(userId, sitemapId, type);
            return Ok();
        }

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

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

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

            return query;
        }

    }
}