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


namespace Sockeye.Api.Controllers
{

    [Route("fetch")]//Legacy v7 license fetch route
    [Produces("application/json")]
    public class FetchController : ControllerBase
    {

        private readonly AyContext ct;
        private readonly ILogger<FetchController> log;
        private readonly ApiServerState serverState;

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


        //////////////////////////////////////////////////////////////////////////
        //########### AyaNova 7.x License fetch route ############
        //For legacy reasons route needs to be named /fetch
        //////////////////////////////////////////////////////////////////////////      
        // GET: fetch/somecode/bob@bob.com
        [HttpGet("{code}/{email}")]
        public async Task<IActionResult> Get([FromRoute] string code, [FromRoute] string email)
        {

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

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

            var rec = await ct.License.SingleOrDefaultAsync(m => m.FetchCode == code.Trim() && m.FetchEmail == email.Trim().ToLowerInvariant() && m.FetchedOn == null);

            if (rec == null)
            {
                //delay, could be someone fishing for a key, make it painful
                //Have verified this is safe, won't affect other jobs on server
                //happening concurrently or other requests to server
                System.Threading.Thread.Sleep(10000);
                return NotFound();
            }
            rec.FetchedOn = System.DateTime.UtcNow;
            await ct.SaveChangesAsync();
            return Ok(rec.Key);
        }


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


    }//eoc
}//eons