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.EntityFrameworkCore;
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}/dashboard-view")]
    [Produces("application/json")]
    [Authorize]
    public class DashboardViewController : ControllerBase
    {
        private readonly AyContext ct;
        private readonly ILogger<DashboardViewController> log;
        private readonly ApiServerState serverState;


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


        /// <summary>
        /// Get DashboardView object for current User
        /// There is always one for each user
        /// </summary>
        /// <returns>Dashboard view</returns>
        [HttpGet()]
        public async Task<IActionResult> GetDashboardView()
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

            //user always has full access to their own dashboard view and can only access their own through api so no need to check
            // 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();
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

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




        /// <summary>
        /// Update logged in User's Dashboard view
        /// </summary>     
        /// <param name="theView"></param>
        /// <returns></returns>
        [HttpPut()]
        public async Task<IActionResult> PutDashboardView([FromBody] string theView)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

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

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

            //user always has full access to their own dashboard view and can only access their own through api so no need to check
            // if (!Authorized.HasModifyRole(HttpContext.Items, biz.BizType))
            //     return StatusCode(403, new ApiNotAuthorizedResponse());

            try
            {
                if (!await biz.PutAsync(o, theView))
                    return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await biz.ExistsAsync())
                    return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
                else
                    return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
            }
            return Ok(ApiOkResponse.Response(new { Concurrency = o.Concurrency }));
        }


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


    }//eoc
}//eons