using System.Threading.Tasks;
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-filter")]
    [Produces("application/json")]
    [Authorize]
    public class DataListSavedFilterController : ControllerBase
    {
        private readonly AyContext ct;
        private readonly ILogger<DataListSavedFilterController> log;
        private readonly ApiServerState serverState;


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


        /// <summary>
        /// Get full DataListSavedFilter object
        /// </summary>
        /// <param name="id"></param>
        /// <returns>A single DataListSavedFilter</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetDataListSavedFilter([FromRoute] long id)
        {
            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));

            //Instantiate the business object handler
            DataListSavedFilterBiz biz = DataListSavedFilterBiz.GetBiz(ct, HttpContext);

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

            var o = await biz.GetAsync(id);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            return Ok(ApiOkResponse.Response(o));
        }



        /// <summary>
        /// Get DataListSavedFilter list
        /// </summary>
        /// <returns>List of public or owned data list views listKey provided</returns>    
        [HttpGet("list", Name = nameof(DataListSavedFilterList))]
        public async Task<IActionResult> DataListSavedFilterList([FromQuery] 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));

            //Instantiate the business object handler
            DataListSavedFilterBiz biz = DataListSavedFilterBiz.GetBiz(ct, HttpContext);

            var l = await biz.GetViewListAsync(ListKey);
            return Ok(ApiOkResponse.Response(l));

        }


        /// <summary>
        /// Update DataListSavedFilter
        /// </summary>
        /// <param name="updatedObject"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> PutDataListSavedFilter([FromBody] DataListSavedFilter updatedObject)
        {
            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));

            //Instantiate the business object handler       
            DataListSavedFilterBiz biz = DataListSavedFilterBiz.GetBiz(ct, HttpContext);

            var o = await biz.PutAsync(updatedObject);
            if (o == null)
            {
                if (biz.Errors.Exists(z => z.Code == ApiErrorCode.CONCURRENCY_CONFLICT))
                    return StatusCode(409, new ApiErrorResponse(biz.Errors));
                else
                    return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            return Ok(ApiOkResponse.Response(new { Concurrency = o.Concurrency }));

        }


        /// <summary>
        /// Create DataListSavedFilter
        /// </summary>
        /// <param name="inObj"></param>
        /// <param name="apiVersion">From route path</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PostDataListSavedFilter([FromBody] DataListSavedFilter inObj, 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));

            //Instantiate the business object handler
            DataListSavedFilterBiz biz = DataListSavedFilterBiz.GetBiz(ct, HttpContext);


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

            //Default filters can never be created from outside
            //they are only ever created from inside so a post with a default=true is always invalid
            if (inObj.DefaultFilter == true)
            {
                return BadRequest(new ApiErrorResponse(ApiErrorCode.INVALID_OPERATION, "default", "Default filters can only be created internally"));
            }

            //Create and validate
            DataListSavedFilter o = await biz.CreateAsync(inObj);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return CreatedAtAction(nameof(DataListSavedFilterController.GetDataListSavedFilter), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));

        }


        /// <summary>
        /// Delete DataListSavedFilter
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Ok</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteDataListSavedFilter([FromRoute] long id)
        {
            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));

            //Instantiate the business object handler
            DataListSavedFilterBiz biz = DataListSavedFilterBiz.GetBiz(ct, HttpContext);

            var o = await biz.GetAsync(id);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            if (!await biz.DeleteAsync(o))
                return BadRequest(new ApiErrorResponse(biz.Errors));

            return NoContent();
        }



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


    }//eoc
}//eons