using GreadyPoang.EntityLayer;
using SQLite;

namespace GreadyPoang.DataLayer;

public class LocalDbService
{
    private const string DB_NAME = "PoangDB";
    private readonly SQLiteAsyncConnection _connection;

    public LocalDbService()
    {
        //string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DB_NAME);  
        string dbPath = Path.Combine(FileSystem.Current.AppDataDirectory, DB_NAME);
        _connection = new SQLiteAsyncConnection(dbPath);
        _connection.CreateTableAsync<Participant>().Wait();
    }

    public async Task<List<Participant>> GetParticipantsAsync()
    {
        return await _connection.Table<Participant>().ToListAsync();
    }

    public async Task<Participant?> GetParticipantAsync(int id)
    {
        return await _connection.Table<Participant>().Where(p => p.ParticipantId == id).FirstOrDefaultAsync();
    }

    public async Task<int> SaveParticipantAsync(Participant participant)
    {
        if (participant.ParticipantId != 0)
        {
            return await _connection.UpdateAsync(participant);
        }
        else
        {
            return await _connection.InsertAsync(participant);
        }
    }

    public async Task<int> DeleteParticipantAsync(Participant participant)
    {
        return await _connection.DeleteAsync(participant);
    }

}
