using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Sockeye.Models;
using Sockeye.Api.ControllerHelpers;
using Sockeye.Biz;

namespace Sockeye.Api.Controllers
{

    /// <summary>
    /// 
    /// </summary>
    [ApiController]
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/data-list-column-view")]
    [Produces("application/json")]
    [Authorize]
    public class DataListColumnViewController : ControllerBase
    {
        private readonly AyContext ct;
        private readonly ILogger<DataListColumnViewController> log;
        private readonly ApiServerState serverState;


        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="dbcontext"></param>
        /// <param name="logger"></param>
        /// <param name="apiServerState"></param>  
        public DataListColumnViewController(AyContext dbcontext, ILogger<DataListColumnViewController> logger, ApiServerState apiServerState)
        {
            ct = dbcontext;
            log = logger;
            serverState = apiServerState;
        }


        /// <summary>
        /// Get DataListColumnView for current user
        /// </summary>        
        /// <param name="listKey"></param>
        /// <returns>DataListColumnView</returns>
        [HttpGet("{listKey}")]
        public async Task<IActionResult> GetDataListColumnView([FromRoute] string listKey)
        {
            if (!serverState.IsOpen && UserIdFromContext.Id(HttpContext.Items) != 1)//bypass for superuser to fix fundamental problems
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            DataListColumnViewBiz biz = DataListColumnViewBiz.GetBiz(ct, HttpContext);

            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            var o = await biz.GetAsync(biz.UserId, listKey, true);
            if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            return Ok(ApiOkResponse.Response(o));
        }



        /// <summary>
        /// Replace DataListColumnView
        /// </summary>
        /// <param name="newObject"></param>
        /// <param name="apiVersion">From route path</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ReplaceDataListColumnView([FromBody] DataListColumnView newObject, ApiVersion apiVersion)
        {
            if (!serverState.IsOpen && UserIdFromContext.Id(HttpContext.Items) != 1)//bypass for superuser to fix fundamental problems
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            DataListColumnViewBiz biz = DataListColumnViewBiz.GetBiz(ct, HttpContext);

            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            DataListColumnView o = await biz.CreateAsync(newObject);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return Ok(ApiOkResponse.Response(o));
        }


        /// <summary>
        /// Reset DataListColumnView to factory defaults
        /// </summary>        
        /// <param name="listKey"></param>
        /// <returns>Default DataListColumnView</returns>
        [HttpDelete("{listKey}")]
        public async Task<IActionResult> ResetDataListColumnView([FromRoute] string listKey)
        {
            if (!serverState.IsOpen && UserIdFromContext.Id(HttpContext.Items) != 1)//bypass for superuser to fix fundamental problems
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            DataListColumnViewBiz biz = DataListColumnViewBiz.GetBiz(ct, HttpContext);
            var o = await biz.DeleteAsync(biz.UserId, listKey);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            return Ok(ApiOkResponse.Response(o));
        }


       

        /// <summary>
        /// Update sort order for user's CoulumnView for DataList key specified
        /// </summary>
        /// <param name="sortRequest">e.g.{"listKey":"CustomerDataList","sortBy":["CustomerPhone1","CustomerEmail"],"sortDesc":[false,false]}</param>
        /// <param name="apiVersion">From route path</param>
        /// <returns></returns>
        [HttpPost("sort")]
        public async Task<IActionResult> SetSort([FromBody] DataListSortRequest sortRequest, ApiVersion apiVersion)
        {
            if (!serverState.IsOpen && UserIdFromContext.Id(HttpContext.Items) != 1)//bypass for superuser to fix fundamental problems
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            DataListColumnViewBiz biz = DataListColumnViewBiz.GetBiz(ct, HttpContext);

            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
          if(!await biz.SetSort(sortRequest))            
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return Ok();
        }
         public record SortRequest(string ListKey, string[] sortBy, bool[] sortDesc);
        //{"listKey":"CustomerDataList","sortBy":["CustomerPhone1","CustomerEmail"],"sortDesc":[false,false]}

        //------------


    }//eoc
}//eons