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;
using System;


namespace Sockeye.Api.Controllers
{
    [ApiController]
    [ApiVersion("8.0")]
    [Route("api/v{version:apiVersion}/integration")]
    [Produces("application/json")]
    [Authorize]
    public class IntegrationController : ControllerBase
    {
        /*
       todo: needs routes for logging and fetching log to view, also mapping collection stuff perhaps??

       */
        private readonly AyContext ct;
        private readonly ILogger<IntegrationController> log;
        private readonly ApiServerState serverState;

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

        /// <summary>
        /// Create Integration
        /// </summary>
        /// <param name="newObject"></param>
        /// <param name="apiVersion">From route path</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PostIntegration([FromBody] Integration newObject, ApiVersion apiVersion)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            Integration o = await biz.CreateAsync(newObject);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return CreatedAtAction(nameof(IntegrationController.GetIntegration), new { integrationAppId = o.IntegrationAppId, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
        }


        /// <summary>
        /// Get Integration
        /// </summary>
        /// <param name="integrationAppId"></param>
        /// <returns>Integration</returns>
        [HttpGet("{integrationAppId}")]
        public async Task<IActionResult> GetIntegration([FromRoute] Guid integrationAppId)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            IntegrationBiz biz = IntegrationBiz.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(integrationAppId, true);
            if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            return Ok(ApiOkResponse.Response(o));
        }

        /// <summary>
        /// Get Integration by DB Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Integration</returns>
        [HttpGet("by-dbid/{id}")]
        public async Task<IActionResult> GetIntegrationByDbId([FromRoute] long id)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            IntegrationBiz biz = IntegrationBiz.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(id, true);
            if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            return Ok(ApiOkResponse.Response(o));
        }




        /// <summary>
        /// Update Integration to db and return it
        /// </summary>        
        /// <param name="updatedObject"></param>
        /// <returns>Entire integration object (differs from most object routes which only return concurrency value)</returns>
        [HttpPut]
        public async Task<IActionResult> PutIntegration([FromBody] Integration updatedObject)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            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(o)); ;
        }

        /// <summary>
        /// Delete Integration
        /// </summary>
        /// <param name="integrationAppId"></param>
        /// <returns>NoContent</returns>
        [HttpDelete("{integrationAppId}")]
        public async Task<IActionResult> DeleteIntegration([FromRoute] Guid integrationAppId)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasDeleteRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!await biz.DeleteAsync(integrationAppId))
                return BadRequest(new ApiErrorResponse(biz.Errors));
            return NoContent();
        }

        /// <summary>
        /// Delete Integration
        /// </summary>
        /// <param name="id"></param>
        /// <returns>NoContent</returns>
        [HttpDelete("by-dbid/{id}")]
        public async Task<IActionResult> DeleteIntegrationByDbId([FromRoute] long id)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasDeleteRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!await biz.DeleteAsync(id))
                return BadRequest(new ApiErrorResponse(biz.Errors));
            return NoContent();
        }





        /// <summary>
        /// Check Integration existance
        /// </summary>
        /// <param name="integrationAppId"></param>
        /// <returns>Integration</returns>
        [HttpGet("exists/{integrationAppId}")]
        public async Task<IActionResult> GetIntegrationExistance([FromRoute] Guid integrationAppId)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));

            return Ok(ApiOkResponse.Response(await biz.ExistsByIntegrationAppIdAsync(integrationAppId)));
        }


        /// <summary>
        /// Create Integration log entry
        /// </summary>
        /// <param name="logItem">id=Integration internal Id (not IntegrationAppId value), name = status text to log</param>
        /// <param name="apiVersion">From route path</param>
        /// <returns>NoContent if ok otherwise BadRequest and an error object</returns>
        [HttpPost("log")]
        public async Task<IActionResult> PostIntegrationLog([FromBody] NameIdItem logItem, ApiVersion apiVersion)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            bool bResult = await biz.LogAsync(logItem);
            if (bResult == false)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return NoContent();
        }

        /// <summary>
        /// Get Integration log for id of integration specified
        /// </summary> 
        /// <returns>All log entries available for integration id</returns>
        [HttpGet("log/{id}")]
        public async Task<IActionResult> GetAllLogs([FromRoute] long id)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            IntegrationBiz biz = IntegrationBiz.GetBiz(ct, HttpContext);
            if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
                return StatusCode(403, new ApiNotAuthorizedResponse());
            if (!ModelState.IsValid)
                return BadRequest(new ApiErrorResponse(ModelState));
            return Ok(ApiOkResponse.Response(await biz.GetLogAsync(id)));
        }



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


    }//eoc
}//eons