using EnotaryoPH.Data;
using EnotaryoPH.Web.Common.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using NsEntities = EnotaryoPH.Data.Entities;

namespace EnotaryoPH.Web.Pages.Principal.IdentificationDocument
{
    public class IdentificationDocumentModel : PageModel
    {
        private readonly ICurrentUserService _currentUserService;
        private readonly NotaryoDBContext _notaryoDBContext;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public IdentificationDocumentModel(IWebHostEnvironment webHostEnvironment, NotaryoDBContext notaryoDBContext, ICurrentUserService currentUserService)
        {
            _webHostEnvironment = webHostEnvironment;
            _notaryoDBContext = notaryoDBContext;
            _currentUserService = currentUserService;
        }

        public IActionResult OnGet()
        {
            if (IdentificationDocument_UID != Guid.Empty)
            {
                var user = _notaryoDBContext.Users.AsNoTracking().FirstOrDefault(u => u.User_UID == _currentUserService.GetUser_UID());

                var document = _notaryoDBContext.IdentificationDocuments.AsNoTracking().FirstOrDefault(d => d.IdentificationDocument_UID == IdentificationDocument_UID && d.UserID == user.UserID);
                if (document == null)
                {
                    return NotFound();
                }

                IdentificationDocument = new Common.Models.IdentificationDocumentModel(document);
            }
            else
            {
                IdentificationDocument = new Common.Models.IdentificationDocumentModel();
            }
            LoadIdentificationDocumentTypes();
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return PostbackPage();
            }

            if (IdentificationDocument.ExpirationDate <= DateTime.Now)
            {
                ModelState.AddModelError(FullName.Of(IdentificationDocument.ExpirationDate), "Your Identification Document has expired");
                return PostbackPage();
            }

            if (IdentificationDocument.DateIssued > DateTime.Now)
            {
                ModelState.AddModelError(FullName.Of(IdentificationDocument.DateIssued), "Your Identification Document has not yet been issued");
                return PostbackPage();
            }

            var user = _notaryoDBContext.Users.AsNoTracking().FirstOrDefault(u => u.User_UID == _currentUserService.GetUser_UID());
            var entity = new NsEntities.IdentificationDocument();
            if (IdentificationDocument_UID != Guid.Empty)
            {
                entity = _notaryoDBContext.IdentificationDocuments.FirstOrDefault(e => e.IdentificationDocument_UID == IdentificationDocument_UID && e.UserID == user.UserID);
                if (entity == null)
                {
                    return BadRequest();
                }
            }
            entity.UploadedOn = DateTime.UtcNow;
            entity = IdentificationDocument.ToEntity(entity);

            if (entity.IdentificationDocumentID > 0)
            {
                _notaryoDBContext.Update(entity);
            }
            else
            {
                entity.UserID = user.UserID;
                entity.CreatedOn = DateTime.UtcNow;
                entity.IdentificationDocument_UID = Guid.CreateVersion7(DateTime.UtcNow);
                _notaryoDBContext.Add(entity);
            }
            _notaryoDBContext.SaveChanges();
            return RedirectToPage("/Principal/Dashboard/Dashboard");
        }

        public IActionResult OnPostDeleteIdentificationDocument()
        {
            if (IdentificationDocument_UID == Guid.Empty)
            {
                return BadRequest();
            }

            var user = _notaryoDBContext.Users.AsNoTracking().FirstOrDefault(u => u.User_UID == _currentUserService.GetUser_UID());
            _notaryoDBContext.IdentificationDocuments.Remove(_notaryoDBContext.IdentificationDocuments.FirstOrDefault(id => id.IdentificationDocument_UID.Value == IdentificationDocument_UID && id.UserID == user.UserID));
            _notaryoDBContext.SaveChanges();

            return new OkObjectResult(true);
        }

        [AllowAnonymous]
        public IActionResult OnGetViewImage()
        {
            if (IdentificationDocument_UID == Guid.Empty)
            {
                return NotFound();
            }

            var identificationDocument = _notaryoDBContext.IdentificationDocuments.FirstOrDefault(e => e.IdentificationDocument_UID == IdentificationDocument_UID);
            if (identificationDocument == null)
            {
                return NotFound();
            }

            return File(identificationDocument.File, "image/jpg");
        }

        private void LoadIdentificationDocumentTypes()
        {
            var lookupIdentificationTypes = _notaryoDBContext.LookupData.AsNoTracking().Include(e => e.LookupDataValues).FirstOrDefault(e => e.Name == "Identification Types");
            IdentificationDocument.IdentificationTypes = lookupIdentificationTypes.LookupDataValues
                .ConvertAll(m => new SelectListItem
                {
                    Text = m.Title.DefaultIfEmpty(m.Value),
                    Value = m.Value
                });
        }

        private IActionResult PostbackPage()
        {
            LoadIdentificationDocumentTypes();
            return Page();
        }

        [BindProperty]
        public Common.Models.IdentificationDocumentModel IdentificationDocument { get; set; }

        [BindProperty(SupportsGet = true)]
        public Guid IdentificationDocument_UID { get; set; }
    }
}