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>
    /// 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 && UserIdFromContext.Id(HttpContext.Items) != 1)//bypass for superuser to fix fundamental problems
            {
                //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)
            {
                //Not users own options so need to check just as for User object as could be a Contact

                //Also used for Contacts (customer type user or ho type user)
                //by users with no User right so further biz rule required depending on usertype
                //this is just phase 1
                bool AllowedOutsideUser = Authorized.HasReadFullRole(HttpContext.Items, SockType.Customer);
                bool AllowedInsideUser = Authorized.HasReadFullRole(HttpContext.Items, SockType.User);

                if (!AllowedOutsideUser && !AllowedInsideUser)
                    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));
        }



        //Creating a user creates a user options so no need for create ever
        // /// <summary>
        // /// Create UserOptions
        // /// </summary>
        // /// <param name="newObject"></param>
        // /// <param name="apiVersion">From route path</param>
        // /// <returns></returns>
        // [HttpPost]
        // public async Task<IActionResult> PostUserOptions([FromBody] UserOptions newObject, ApiVersion apiVersion)
        // {
        //     if (!serverState.IsOpen)
        //         return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
        //     // var UserId = UserIdFromContext.Id(HttpContext.Items);

        //     // //preclearance
        //     // //the biz object will further check
        //     // if (newObject.Id != UserId)
        //     // {
        //     //     //Also used for Contacts (customer type user or ho type user)
        //     //     //by users with no User right so further biz rule required depending on usertype
        //     //     //this is just phase 1
        //     //     if (!Authorized.HasCreateRole(HttpContext.Items, SockType.User) && !Authorized.HasCreateRole(HttpContext.Items, SockType.Customer))
        //     //         return StatusCode(403, new ApiNotAuthorizedResponse());
        //     // }
        //     UserOptionsBiz biz = new UserOptionsBiz(ct, UserIdFromContext.Id(HttpContext.Items), UserRolesFromContext.Roles(HttpContext.Items));

        //     if (!ModelState.IsValid)
        //         return BadRequest(new ApiErrorResponse(ModelState));
        //     UserOptions o = await biz.CreateAsync(newObject);
        //     if (o == null)
        //         return BadRequest(new ApiErrorResponse(biz.Errors));
        //     else
        //         return CreatedAtAction(nameof(UserOptionsController.GetUserOptions), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
        // }


        /// <summary>
        /// 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 && 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));

            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));
            }

            //preclearance
            //the biz object will further check
            if (id != UserId)
            {
                //Also used for Contacts (customer type user or ho type user)
                //by users with no User right so further biz rule required depending on usertype
                //this is just phase 1
                if (!Authorized.HasModifyRole(HttpContext.Items, SockType.User) && !Authorized.HasModifyRole(HttpContext.Items, SockType.Customer))
                    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