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

namespace Sockeye.Api.Controllers
{

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



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

        /// <summary>
        /// Get GlobalBizSettings
        /// </summary>      
        /// <returns>Global settings object</returns>
        [HttpGet]
        public async Task<IActionResult> GetGlobalBizSettings()
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

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


        /// <summary>
        /// PUT Global biz settings   
        /// </summary>       
        /// <param name="updatedObject"></param>
        /// <returns>New concurrency token</returns>      
        [HttpPut]
        public async Task<IActionResult> ReplaceGlobalBizSettings([FromBody] GlobalBizSettings updatedObject)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

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

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

            var o = await biz.PutAsync(updatedObject);
            if (o == null)
                return StatusCode(409, new ApiErrorResponse(biz.Errors));
            return Ok(ApiOkResponse.Response(new { Concurrency = o.Concurrency }));
        }

        /// <summary>
        /// Get Client app relevant GlobalBizSettings
        /// </summary>      
        /// <returns>Global settings object</returns>
        [HttpGet("client")]
        public ActionResult GetClientGlobalBizSettings()
        {
            //## NOTE: these are settings that the Client needs to see for standard operations
            //NOT the settings that the user changes in the global settings form which is fetched above
            //so do not include anything here unless the client needs it
            if (serverState.IsClosed)
            {
                //Exception for SuperUser account to handle licensing issues
                if (UserIdFromContext.Id(HttpContext.Items) != 1)
                    return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
            }



            var ret = new
            {
                //Actual global settings:
                FilterCaseSensitive = Sockeye.Util.ServerGlobalBizSettings.Cache.FilterCaseSensitive,
                Company = "GZTW"
            };

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

        [HttpPost("permanently-erase-all-data")]
        public async Task<IActionResult> RemoveAllData([FromBody] string acceptCode)
        {
            if (serverState.IsClosed)
                return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

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

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

            //SuperUser only and must have accept code
            if (string.IsNullOrWhiteSpace(acceptCode) || acceptCode.ToLowerInvariant() != "i bloody understand")
                return StatusCode(403, new ApiNotAuthorizedResponse());



            //empty the db
            await Sockeye.Util.DbUtil.EmptyBizDataFromDatabaseForSeedingOrImportingAsync(log);

            //Log
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(1, 0, SockType.Global, SockEvent.EraseAllData), ct);

            return NoContent();
        }

        //USE PERMANENTLY ERASE DATABASE ON STARTUP INSTEAD OF THIS TO IMPORT

        // /// <summary>
        // /// import data from rockfish that isn't already present
        // /// </summary>
        // /// <returns>No content</returns>
        // [HttpPost("import-rockfish")]
        // public async Task<IActionResult> ImportRockfish([FromBody] Customer newObject, ApiVersion apiVersion)
        // {
        //     if (!serverState.IsOpen)
        //         return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));

        //     GlobalBizSettingsBiz biz = GlobalBizSettingsBiz.GetBiz(ct, HttpContext);
        //     await biz.ImportRockfish(log);
        //     return NoContent();
        // }




    }//eoc
}//ens