using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using rockfishCore.Models;
using rockfishCore.Util;

namespace rockfishCore.Controllers
{
    [Produces("text/plain")]
    [Route("fetch")]

    public class FetchController : Controller
    {
        private readonly rockfishContext _context;

        public FetchController(rockfishContext context)
        {
            _context = context;
        }



        // GET: fetch/somecode/bob@bob.com
        [HttpGet("{code}/{email}")]
        public async Task<IActionResult> Get([FromRoute] string code, [FromRoute] string email)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var rec = await _context.License.SingleOrDefaultAsync(m => m.Code == code.Trim() && m.Email == email.Trim().ToLowerInvariant() && m.Fetched == false);

            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.Fetched = true;
            rec.DtFetched = DateUtil.NowAsEpoch();
            //This might be flaky if behind some other stuff
            //rec.FetchFrom = HttpContext.Connection.RemoteIpAddress.ToString();
            _context.Entry(rec).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LicenseExists(rec.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok(rec.Key);
            //return Ok(new {key=rec.Key});
        }





        private bool LicenseExists(long id)
        {
            return _context.License.Any(e => e.Id == id);
        }
    }
}