using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Sockeye.Models;
using Sockeye.Api.ControllerHelpers;
using Sockeye.Biz;
using Sockeye.PickList;
using System.Threading.Tasks;
using System.Linq;

namespace Sockeye.Api.Controllers
{

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



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



        /// <summary>
        /// Get picklist of all Active objects of type specified and filtered by query specified
        /// NOTE: Query is valid only if:
        /// it is an empty string indicating not filtered just selected
        /// if not an empty string, it has at most two space separated strings and one of them is a special TAG specific query that starts with two consecutive periods 
        /// i.e. "some" is valid (single query on all templated fields) 
        /// "..zon some" is valid (all tags like zon and all template fields like some)
        /// "zon some" is NOT valid (missing TAGS indicator), "..zone some re" is NOT valid (too many strings)
        /// Note that this list is capped automatically to return no more than 100 results
        /// </summary>
        /// <param name="pickListParams">Parameters for pick list see api docs for details </param>
        /// <returns>Filtered list</returns>
        [HttpPost("list")]
        public async Task<IActionResult> PostList([FromBody] PickListOptions pickListParams)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

            //NOTE: these sequence of calls are a little different than other objects due to the nature of rights and stuff with picklists being different

            var PickList = PickListFactory.GetAyaPickList(pickListParams.SockType);

            //was the name not found as a pick list?
            if (PickList == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            //RIGHTS - NOTE: uniquely to other routes this one checks the actual picklist defined roles itself
            if (!Authorized.HasAnyRole(HttpContext.Items, PickList.AllowedRoles))
                return StatusCode(403, new ApiNotAuthorizedResponse());


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




            //handle HeadOffice only restricted variants
            if (pickListParams.ListVariant == "ho")
            {
                //add a variant for the current user's head office id in place of ho
                var UserId = UserIdFromContext.Id(HttpContext.Items);
                var UType = UserTypeFromContext.Type(HttpContext.Items);
                if (UType != UserType.HeadOffice)
                    return StatusCode(403, new ApiNotAuthorizedResponse());
                var HoId = await ct.User.AsNoTracking().Where(x => x.Id == UserId).Select(x => x.HeadOfficeId).SingleOrDefaultAsync();
                if (HoId == null || HoId == 0)
                    return StatusCode(403, new ApiNotAuthorizedResponse());
                pickListParams.ListVariant = $"{HoId},{(int)SockType.HeadOffice}";

            }

            var o = await biz.GetPickListAsync(PickList, pickListParams.Query, pickListParams.Inactive, pickListParams.PreselectedIds.ToArray(), pickListParams.ListVariant, log, pickListParams.Template);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return Ok(ApiOkResponse.Response(o));
        }



        /// <summary>
        /// Get a single item's name display in PickList templated format
        /// </summary>
        /// <param name="pickListSingleParams"></param>
        /// <returns>One display string or an empty string if not found or invalid</returns>
        [HttpPost("single")]
        public async Task<IActionResult> PostSingle([FromBody] PickListSingleOptions pickListSingleParams)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

            if (!Authorized.HasSelectRole(HttpContext.Items, pickListSingleParams.SockType))
                return StatusCode(403, new ApiNotAuthorizedResponse());

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

            var o = await biz.GetTemplatedNameAsync(pickListSingleParams.SockType, pickListSingleParams.Id, pickListSingleParams.ListVariant, log, pickListSingleParams.Template);
            if (o == null)
                return BadRequest(new ApiErrorResponse(biz.Errors));
            else
                return Ok(ApiOkResponse.Response(o));
        }


        /// <summary>
        /// Get PickListTemplate
        /// </summary>
        /// <param name="sockType"></param>
        /// <returns>The current effective template, either a customized one or the default</returns>
        [HttpGet("template/{sockType}")]
        public async Task<IActionResult> GetPickListTemplate([FromRoute] SockType sockType)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

            //Instantiate the business object handler
            PickListBiz biz = PickListBiz.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(sockType);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

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



        /// <summary>
        /// List of all PickList templates
        /// </summary>        
        /// <returns>List of strings</returns>
        [HttpGet("template/list")]
        public ActionResult GetTemplateList()
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

            long TranslationId = UserTranslationIdFromContext.Id(HttpContext.Items);
            var o = biz.GetListOfAllPickListTypes(TranslationId);
            if (o == null)
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));

            return Ok(ApiOkResponse.Response(o));

        }




        /// <summary>
        /// POST (replace) Pick List template
        /// (note: in this case the Id is the SockType numerical value as there is only one template per type)
        /// </summary>       
        /// <param name="template"></param>
        /// <returns></returns>
       // [HttpPost("Template/{sockType}")]
        [HttpPost("template")]
        public async Task<IActionResult> ReplacePickListTemplate([FromBody] PickListTemplate template)
        {
            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       
            PickListBiz biz = PickListBiz.GetBiz(ct, HttpContext);

            // var o = await biz.GetAsync(sockType, false);
            // 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.ReplaceAsync(template))
                    return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            catch (DbUpdateConcurrencyException)
            {

                return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
            }
            return NoContent();
        }


        /// <summary>
        /// Delete customized template
        /// (revert to default)
        /// </summary>
        /// <param name="sockType"></param>
        /// <returns>Ok</returns>
        [HttpDelete("template/{sockType}")]
        public async Task<IActionResult> DeletePickListTemplate([FromRoute] SockType sockType)
        {
            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
            PickListBiz biz = PickListBiz.GetBiz(ct, HttpContext);


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

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

            return NoContent();
        }


        /// <summary>
        /// List of all fields for pick list SockType specified
        /// </summary>        
        /// <returns>List of fields available for template</returns>
        [HttpGet("template/listfields/{sockType}")]
        public ActionResult GetPickListFields([FromRoute] SockType sockType)
        {
            if (!serverState.IsOpen)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

            var PickList = PickListFactory.GetAyaPickList(sockType);
            //type might not be supported
            if (PickList == null)
            {
                return BadRequest(new ApiErrorResponse(ApiErrorCode.NOT_FOUND, null, $"PickList for type  \"{sockType.ToString()}\" not supported"));
            }
            return Ok(ApiOkResponse.Response(PickList.ColumnDefinitions));
        }






    }//eoc
}//ens