using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;


namespace AyaNova.Api.Controllers
{

    /// <summary>
    /// Search
    /// </summary>
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [Produces("application/json")]
    [Authorize]
    public class SearchController : Controller
    {
        private readonly AyContext ct;
        private readonly ILogger<WidgetController> log;
        private readonly ApiServerState serverState;

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



        /// <summary>
        /// Post search parameters
        /// Required roles: Any 
        /// MaxResults defaults to 500 
        /// MaxResults = 0 returns all results 
        /// There is no paging as this is a dynamic response 
        /// 
        /// </summary>
        /// <param name="searchParams"></param>
        /// <returns>SearchResult list</returns>
        [HttpPost]
        public async Task<IActionResult> PostSearch([FromBody] Search.SearchRequestParameters searchParams)
        {
            if (!serverState.IsOpen)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(new ApiErrorResponse(ModelState));
            }

            //Do the search
            var SearchResults = await Search.DoSearch(ct, UserLocaleIdFromContext.Id(HttpContext.Items), UserRolesFromContext.Roles(HttpContext.Items), searchParams);

            return Ok(new ApiOkResponse(SearchResults));
        }



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


    }//eoc
}//eons