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 AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;


namespace AyaNova.Api.Controllers
{

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


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


        /// <summary>
        /// Get full UserOptions object
        /// </summary>
        /// <param name="id">UserId</param>
        /// <returns>A single UserOptions</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetUserOptions([FromRoute] long id)
        {
            if (!serverState.IsOpen)
            {
                //Exception for SuperUser account to handle licensing issues
                if (UserIdFromContext.Id(HttpContext.Items) != 1)
                    return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            }

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

            var UserId = UserIdFromContext.Id(HttpContext.Items);

            //Different than normal here: a user is *always* allowed to retrieve their own user options object
            if (id != UserId && !Authorized.HasReadFullRole(HttpContext.Items, AyaType.UserOptions))
            {
                return StatusCode(403, new ApiNotAuthorizedResponse());
            }

            //Instantiate the business object handler
            UserOptionsBiz biz = new UserOptionsBiz(ct, UserId, UserRolesFromContext.Roles(HttpContext.Items));

            var o = await biz.GetAsync(id);

            if (o == null)
            {
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            }

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




        /// <summary>
        /// Put (update) UserOptions
        /// </summary>
        /// <param name="id">User id</param>
        /// <param name="inObj"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> PutUserOptions([FromRoute] long id, [FromBody] UserOptions inObj)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

            if (!ModelState.IsValid)
            {
                return BadRequest(new ApiErrorResponse(ModelState));
            }
            var UserId = UserIdFromContext.Id(HttpContext.Items);

            var o = await ct.UserOptions.SingleOrDefaultAsync(z => z.UserId == id);

            if (o == null)
            {
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            }

            if (id != UserId && !Authorized.HasModifyRole(HttpContext.Items, AyaType.UserOptions))
            {
                return StatusCode(403, new ApiNotAuthorizedResponse());
            }

            //Instantiate the business object handler       
            UserOptionsBiz biz = new UserOptionsBiz(ct, UserIdFromContext.Id(HttpContext.Items), UserRolesFromContext.Roles(HttpContext.Items));

            try
            {
                if (!await biz.PutAsync(o, inObj))
                {
                    return BadRequest(new ApiErrorResponse(biz.Errors));
                }
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserOptionsExists(id))
                {
                    return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
                }
                else
                {
                    //exists but was changed by another user                   
                    return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
                }
            }

            return Ok(ApiOkResponse.Response(new { Concurrency = o.Concurrency }));
        }



        private bool UserOptionsExists(long id)
        {
            //NOTE: checks by UserId, NOT by Id as in most other objects
            return ct.UserOptions.Any(z => z.UserId == id);
        }


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


    }//eoc
}//eons