using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace sotd.Pages;

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    [BindProperty]
    public List<SongSuggestion> SongSuggestions { get; set; } = new List<SongSuggestion>();

    private User _currentUser;

    public User CurrentUser
    {
        get
        {
            if (_currentUser == null)
            {
                var userName = this.User.Identity.Name;
                using (var dci = DataContext.Instance)
                {
                    _currentUser = dci.Users.Include(u => u.LikedSongs).Where(u => u.LdapUserName == userName).SingleOrDefault();
                }
            }

            return _currentUser;
        }

    }

    public bool HasUserLikedThisSong(Song song)
    {
        return CurrentUser.LikedSongs.Where(s => s.SongId == song.SongId).FirstOrDefault() != default(Song);
    }

    public Task OnGet()
    {
        using var dci = DataContext.Instance;
        SongSuggestions = dci.SongSuggestions.OrderByDescending(s => s.Date)
            .Take(50)
            .Include(s => s.Song)
            .Include(s => s.User)
            .ToList();
        return Task.CompletedTask;
    }

    public async Task<IActionResult> OnPostLikeSong(int? songId)
    {
        using (var dci = DataContext.Instance)
        {
            var user = dci.Users.Include(u => u.LikedSongs).Where(u => u.UserId == CurrentUser.UserId).SingleOrDefault();
            if (user.LikedSongs.Find(s => s.SongId == songId) == default(Song))
            {
                user.LikedSongs.Add(dci.Songs.Find(songId));
                await dci.SaveChangesAsync();
            }
        }
        return RedirectToPage("/");
    }

    public async Task<IActionResult> OnPostUnlikeSong(int? songId)
    {
        using (var dci = DataContext.Instance)
        {
            var user = dci.Users.Include(u => u.LikedSongs).Where(u => u.UserId == CurrentUser.UserId).SingleOrDefault();
            var songToRemove = user.LikedSongs.Where(s => s.SongId == songId).SingleOrDefault();
            if (songToRemove != default(Song))
            {
                user.LikedSongs.Remove(songToRemove);
                await dci.SaveChangesAsync();
            }
        }
        return RedirectToPage("/");
    }
}
