using System.Diagnostics;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Sequence.Entities;
using Sequence.Models;

namespace Sequence.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly DbContext dbContext;

    public HomeController(ILogger<HomeController> logger, DbContext dbContext)
    {
        _logger = logger;
        this.dbContext = dbContext;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Board()
    {
        var userId = Guid.Parse("08db379a-5de8-420d-8232-1bb60fdf249b");

        var match = dbContext.Matches
            .Include(m => m.Deck)
            .Include(m => m.PlayerOne)
            .ThenInclude(p => p.HandCards)
            .Include(m => m.PlayerTwo)
            .ThenInclude(p => p.HandCards)
            .OrderByDescending(m => m.Created)
            .AsSplitQuery()
            .FirstOrDefault(m => m.PlayerOne.UserId == userId || m.PlayerTwo.UserId == userId);



        return View();
    }

    public async Task<IActionResult> CreateMatch(Guid userOneGuid, Guid userTwoGuid)
    {
        var playerOne = new Player
        {
            Alias = "SwiggitySwooty",
            UserId = userOneGuid
        };

        var playerTwo = new Player
        {
            Alias = "BabeFoy",
            UserId = userTwoGuid
        };

        dbContext.Add(playerOne);
        dbContext.Add(playerTwo);

        var match = new Match
        {
            Created = DateTime.Now,
            CurrentTurnPlayerId = playerOne.Id,
            PlayerOneId = playerOne.Id,
            PlayerTwoId = playerTwo.Id
        };

        dbContext.Add(match);

        var deck = dbContext.Cards
            .OrderBy(c => Guid.NewGuid())
            .Select(c => new DeckCard
            {
                CardId = c.Id,
                MatchId = match.Id
            })
            .ToList();

        dbContext.AddRange(deck);

        var handCards = new List<HandCard>();

        for (var i = 1; i <= 14; i += 2)
        {
            var deckCard = deck[i];
            var deckCard2 = deck[i + 1];

            deckCard.Dealt = true;

            handCards.Add(new HandCard
            {
                DeckCardId = deckCard.Id,
                PlayerId = playerOne.Id
            });

            deckCard2.Dealt = true;

            handCards.Add(new HandCard
            {
                DeckCardId = deckCard2.Id,
                PlayerId = playerTwo.Id
            });
        }
        
        dbContext.AddRange(handCards);

        dbContext.SaveChanges();

        throw new NotImplementedException();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
