using System.Collections.Generic;
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.AspNetCore.JsonPatch;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;


namespace AyaNova.Api.Controllers
{
    //DOCUMENTATING THE API
    //https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/recommended-tags-for-documentation-comments
    //https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments

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


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




        /// <summary>
        /// Get Locale all values
        /// 
        /// Required roles: Any 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>A single Locale and it's values</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetLocale([FromRoute] long id)
        {
            if (serverState.IsClosed)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }


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

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

            var o = await biz.GetAsync(id);

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

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



        /// <summary>
        /// Get Locale pick list
        /// Required roles: Any
        /// 
        /// </summary>
        /// <returns>Picklist in alphabetical order of all locales</returns>    
        [HttpGet("PickList")]
        public async Task<IActionResult> LocalePickList()
        {
            if (serverState.IsClosed)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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

            var l = await biz.GetPickListAsync();
            return Ok(ApiOkResponse.Response(l, true));
        }


#if (DEBUG)
        /// <summary>
        /// Get a coverage report of locale keys used versus unused
        /// Required roles: Any
        /// 
        /// </summary>
        /// <returns>Report of all unique locale keys requested since last  server reboot</returns>    
        [HttpGet("LocaleKeyCoverage")]
        public ActionResult LocaleKeyCoverage()
        {
            if (serverState.IsClosed)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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

            var l = biz.LocaleKeyCoverage();
            return Ok(ApiOkResponse.Response(l, true));
        }
#endif


        /// <summary>
        /// Get subset of locale values
        /// Required roles: Any
        /// 
        /// </summary>
        /// <param name="inObj">List of locale key strings</param>
        /// <returns>A key value array of localized text values</returns>    
        [HttpPost("SubSet")]
        public async Task<IActionResult> SubSet([FromBody] List<string> inObj)
        {
            if (serverState.IsClosed)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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

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

            var l = await biz.GetSubset(inObj);
            return Ok(ApiOkResponse.Response(l, true));
        }


        /// <summary>
        /// Duplicates an existing locale with a new name   
        /// 
        /// Required roles: OpsAdminFull | BizAdminFull
        /// 
        /// </summary>
        /// <param name="inObj">NameIdItem object containing source locale Id and new name</param>
        /// <param name="apiVersion">Automatically filled from route path, no need to specify in body</param>
        /// <returns>Error response or newly created locale</returns>    
        [HttpPost("Duplicate")]
        public async Task<IActionResult> Duplicate([FromBody] NameIdItem inObj, ApiVersion apiVersion)
        {
            if (serverState.IsClosed)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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

            var o = await biz.DuplicateAsync(inObj);

            if (o == null)
            {
                //error return
                return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            else
            {
                return CreatedAtAction(nameof(LocaleController.GetLocale), new { id = o.Id, version = apiVersion.ToString()  }, new ApiCreatedResponse(o));
            }
        }



        /// <summary>
        /// Put (UpdateLocaleItemDisplayText) 
        /// 
        /// Required roles: OpsAdminFull | BizAdminFull
        /// 
        /// Update a single key with new display text
        /// 
        /// </summary>     
        /// <param name="inObj">NewText/Id/Concurrency token object. NewText is new display text, Id is LocaleItem Id, concurrency token is required</param>
        /// <returns></returns>
        [HttpPut("UpdateLocaleItemDisplayText")]
        public async Task<IActionResult> PutLocalItemDisplyaText([FromBody] NewTextIdConcurrencyTokenItem inObj)
        {
            if (!serverState.IsOpen)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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

            var oFromDb = await ct.LocaleItem.SingleOrDefaultAsync(m => m.Id == inObj.Id);

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

            //Now fetch locale for rights and to ensure not stock
            var oDbParent = await ct.Locale.SingleOrDefaultAsync(x => x.Id == oFromDb.LocaleId);
            if (oDbParent == null)
            {
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            }

            if (!Authorized.HasModifyRole(HttpContext.Items, AyaType.Locale))
            {
                return StatusCode(403, new ApiNotAuthorizedResponse());
            }

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

            try
            {
                if (!biz.PutLocaleItemDisplayText(oFromDb, inObj, oDbParent))
                {
                    return BadRequest(new ApiErrorResponse(biz.Errors));
                }
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!biz.LocaleItemExists(inObj.Id))
                {
                    return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
                }
                else
                {
                    //exists but was changed by another user
                    //I considered returning new and old record, but where would it end?
                    //Better to let the client decide what to do than to send extra data that is not required
                    return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
                }
            }


            return Ok(ApiOkResponse.Response(new { ConcurrencyToken = oFromDb.ConcurrencyToken }, true));
        }

        /// <summary>
        /// Put (UpdateLocaleName) 
        /// 
        /// Required roles: OpsAdminFull | BizAdminFull
        /// 
        /// Update a locale to change the name (non-stock locales only)
        /// 
        /// </summary>     
        /// <param name="inObj">NewText/Id/Concurrency token object. NewText is new locale name, Id is Locale Id, concurrency token is required</param>
        /// <returns></returns>
        [HttpPut("UpdateLocaleName")]
        public async Task<IActionResult> PutLocaleName([FromBody] NewTextIdConcurrencyTokenItem inObj)
        {
            if (!serverState.IsOpen)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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

            var oFromDb = await ct.Locale.SingleOrDefaultAsync(m => m.Id == inObj.Id);

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


            if (!Authorized.HasModifyRole(HttpContext.Items, AyaType.Locale))
            {
                return StatusCode(403, new ApiNotAuthorizedResponse());
            }

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

            try
            {
                if (!biz.PutLocaleName(oFromDb, inObj))
                {
                    return BadRequest(new ApiErrorResponse(biz.Errors));
                }

            }
            catch (DbUpdateConcurrencyException)
            {
                if (!biz.LocaleExists(inObj.Id))
                {
                    return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
                }
                else
                {
                    //exists but was changed by another user
                    //I considered returning new and old record, but where would it end?
                    //Better to let the client decide what to do than to send extra data that is not required
                    return StatusCode(409, new ApiErrorResponse(ApiErrorCode.CONCURRENCY_CONFLICT));
                }
            }

            return Ok(ApiOkResponse.Response(new { ConcurrencyToken = oFromDb.ConcurrencyToken }, true));
        }


        /// <summary>
        /// Delete Locale
        /// 
        /// Required roles:
        /// BizAdminFull, InventoryFull      
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Ok</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteLocale([FromRoute] long id)
        {

            if (!serverState.IsOpen)
            {
                return StatusCode(503, new ApiErrorResponse(ApiErrorCode.API_CLOSED, null, serverState.Reason));
            }

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


            //Fetch locale and it's children
            //(fetch here so can return proper REST responses on failing basic validity)
            var dbObj = ct.Locale.Include(x => x.LocaleItems).SingleOrDefault(m => m.Id == id);
            if (dbObj == null)
            {
                return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
            }

            if (!Authorized.HasDeleteRole(HttpContext.Items, AyaType.Locale))
            {
                return StatusCode(403, new ApiNotAuthorizedResponse());
            }


            //Instantiate the business object handler
            //LocaleBiz biz = new LocaleBiz(ct, UserIdFromContext.Id(HttpContext.Items), UserRolesFromContext.Roles(HttpContext.Items));
            LocaleBiz biz = LocaleBiz.GetBiz(ct, HttpContext);
            if (!biz.Delete(dbObj))
            {
                return BadRequest(new ApiErrorResponse(biz.Errors));
            }
            //Log
            EventLogProcessor.DeleteObject(biz.UserId, AyaType.Locale, dbObj.Id, dbObj.Name, ct);
            await ct.SaveChangesAsync();

            //Delete children / attached objects 
            //  biz.DeleteChildren(dbObj);



            return NoContent();
        }




        // private bool LocaleExists(long id)
        // {
        //     return ct.Locale.Any(e => e.Id == id);
        // }




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

        // public class LocaleSubsetParam
        // {
        //     [System.ComponentModel.DataAnnotations.Required]
        //     public long LocaleId { get; set; }
        //     [System.ComponentModel.DataAnnotations.Required]
        //     public List<string> Keys { get; set; }

        //     public LocaleSubsetParam()
        //     {
        //         Keys = new List<string>();
        //     }

        // }

#if (DEBUG)
        public class LocaleCoverageInfo
        {
            public List<string> RequestedKeys { get; set; }
            public int RequestedKeyCount { get; set; }
            public List<string> NotRequestedKeys { get; set; }
            public int NotRequestedKeyCount { get; set; }

            public LocaleCoverageInfo()
            {
                RequestedKeys = new List<string>();
                NotRequestedKeys = new List<string>();
            }

        }
#endif

    }
}