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

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


namespace AyaNova.Api.Controllers
{

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


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


        /// <summary>
        /// Get full DataListTemplate object
        /// </summary>
        /// <param name="DataListKey"></param>
        /// <returns>A single DataListTemplate</returns>
        [HttpGet("{DataListKey}")]
        public async Task<IActionResult> GetDataListTemplate([FromRoute] string DataListKey)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));

            //Attempt to get the data list by key to see if key is valid and for the default template and valid field names
            var DataList = DataListFactory.GetAyaDataList(DataListKey);
            if (DataList == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

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

            if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());

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

            var o = await biz.GetAsync(DataListKey, true, DataList);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            return Ok(ApiOkResponse.Response(o, !Authorized.HasModifyRole(HttpContext.Items, biz.BizType)));
        }


        /// <summary>
        /// List of all DataList keys available
        /// </summary>        
        /// <returns>List of strings</returns>
        [HttpGet("ListKeys")]
        public ActionResult GetDataListKeys()
        {
            if (!serverState.IsOpen)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

            return Ok(ApiOkResponse.Response(DataListFactory.GetListOfAllDataListKeyNames(), true));
        }


        /// <summary>
        /// Put (update) DataListTemplate
        /// </summary>
        /// <param name="DataListKey"></param>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPut("{DataListKey}")]
        public async Task<IActionResult> PutDataListTemplate([FromRoute] string DataListKey, [FromBody] DataListTemplate inObj)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));

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

            //Attempt to get the data list by key to see if key is valid and for the default template and valid field names
            var DataList = DataListFactory.GetAyaDataList(DataListKey);
            if (DataList == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

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

            var o = await biz.GetAsync(DataListKey, false, DataList);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());

            try
            {
                if (!await biz.PutAsync(o, inObj, DataList))
                    return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            catch (DbUpdateConcurrencyException)
            {
                // if (!await biz.ExistsAsync(id))
                //     return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
                // else
                //these always exist so can only be concurrency conflict
                return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
            }
            return Ok(ApiOkResponse.Response(new { ConcurrencyToken = o.ConcurrencyToken }, true));
        }



        /// <summary>
        /// Delete DataListTemplate
        /// (Reset DataListTemplate to default)
        /// </summary>
        /// <param name="DataListKey"></param>
        /// <returns>Ok</returns>
        [HttpDelete("{DataListKey}")]
        public async Task<IActionResult> DeleteDataListTemplate([FromRoute] string DataListKey)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));

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

            //Attempt to get the data list by key to see if key is valid 
            var DataList = DataListFactory.GetAyaDataList(DataListKey);
            if (DataList == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

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

            var o = await biz.GetAsync(DataListKey, false, DataList);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            if (!Authorized.HasDeleteRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());

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

            return NoContent();
        }

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


    }//eoc
}//eons