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

namespace Gready_Poang.DataLayer;

public class GamePointRepository : IRepository<GamePoint>
{
    private readonly DataContext _dataContext;

    public GamePointRepository(DataContext dataContext)
    {
        _dataContext = dataContext;
    }
    public async Task<IEnumerable<GamePoint>> Get()
    {
        return await _dataContext.GamePoints.ToListAsync();
    }
    public async Task<GamePoint?> Get(int id)
    {
        return await _dataContext.GamePoints.FindAsync(id);
    }
    public async Task<int> Save(GamePoint entity)
    {
        var res = -1;
        if ((entity.GameRoundRegNr == 0)
            && (entity.GameRegPoints == 0))
        {
            return res; // Validation failed
        }

        if (entity.GamePointId == 0)
        {
            _dataContext.GamePoints.Add(entity);
            await _dataContext.SaveChangesAsync();
            res = entity.GamePointId;
        }
        else
        {
            _dataContext.GamePoints.Update(entity);
            await _dataContext.SaveChangesAsync();
            res = entity.GamePointId;
        }
        return res;
    }

    public bool Delete(GamePoint entity)
    {
        var res = false;
        try
        {
            _dataContext.GamePoints.Remove(entity);
            _dataContext.SaveChangesAsync();
            res = true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"Error deleting participant: {ex.Message}");
            res = false;
        }
        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 GamePoint: " + ex.Message);
            }
        }
        return ok;
    }
}
