package com.example.pap_teste.viewmodels;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.pap_teste.data.AppDatabase;
import com.example.pap_teste.data.ReservationDao;
import com.example.pap_teste.models.LocalReservation;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ReservationViewModel extends AndroidViewModel {
    private final ReservationDao reservationDao;
    private final ExecutorService executorService;
    private final LiveData<List<LocalReservation>> allReservations;

    public ReservationViewModel(@NonNull Application application) {
        super(application);
        AppDatabase db = AppDatabase.getInstance(application);
        reservationDao = db.reservationDao();
        allReservations = reservationDao.getAllReservations();
        executorService = Executors.newSingleThreadExecutor();
    }

    public LiveData<List<LocalReservation>> getAllReservations() {
        return allReservations;
    }

    public void insert(LocalReservation reservation) {
        executorService.execute(() -> reservationDao.insert(reservation));
    }

    public void update(LocalReservation reservation) {
        executorService.execute(() -> reservationDao.update(reservation));
    }

    public void delete(LocalReservation reservation) {
        executorService.execute(() -> reservationDao.delete(reservation));
    }

    public void checkConflict(String date, int tableId, OnConflictCheckListener listener) {
        executorService.execute(() -> {
            List<LocalReservation> conflicts = reservationDao.getReservationsForTable(date, tableId);
            listener.onResult(conflicts.isEmpty());
        });
    }

    public interface OnConflictCheckListener {
        void onResult(boolean isAvailable);
    }
}
