using Common.Library;
using GreadyPoang.DataLayer.Database;
using GreadyPoang.EntityLayer;
using Microsoft.EntityFrameworkCore;

namespace GreadyPoang.DataLayer;

public class GameRoundRepository : IRepository<GameRound>
{
    private readonly DataContext _dataContext;

    public GameRoundRepository(DataContext dataContext)
    {
        _dataContext = dataContext;
    }

    public bool Delete(GameRound entity)
    {
        var res = false;
        try
        {
            _dataContext.GameRounds.Remove(entity);
            _dataContext.SaveChanges();
            res = true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error deleting GameRound: {ex.Message}");
            res = false;
        }
        return res;
    }

    public async Task<IEnumerable<GameRound>> Get()
    {
        return await _dataContext.GameRounds.ToListAsync();
    }

    public async Task<GameRound?> Get(int id)
    {
        return await _dataContext.GameRounds.FindAsync(id);
    }

    public async Task<int> Save(GameRound entity)
    {
        var res = -1;
        if (entity.GameRoundId == 0)
        {
            _dataContext.GameRounds.Add(entity);
            await _dataContext.SaveChangesAsync();
            res = entity.GameRoundId;
        }
        else
        {
            _dataContext.GameRounds.Update(entity);
            await _dataContext.SaveChangesAsync();
            res = entity.GameRoundId;
        }
        return res;
    }

    public async Task<bool> DeleteById(int Id)
    {
        var ok = false;
        var delObject = await this.Get(Id);
        if (delObject != null)
        {

            try
            {
                ok = this.Delete(delObject);
            }
            catch (Exception ex)
            {
                throw new Exception("Unsuccessful remove of GameRound: " + ex.Message);
            }
        }
        return ok;
    }

}
