package com.m2sdl.undercooked.services;

import android.widget.LinearLayout;

import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.m2sdl.undercooked.domain.Booking;
import com.m2sdl.undercooked.domain.Review;

import java.util.ArrayList;
import java.util.List;

public class FirebaseBackendService {

    private final FirebaseFirestore db;

    public FirebaseBackendService() {
        db = FirebaseFirestore.getInstance();
    }

    public Task<DocumentReference> addBooking(Booking booking) {
        return db.collection("bookings").add(booking);
    }

    public Task<DocumentReference> addReview(Review review) {
        return db.collection("reviews").add(review);
    }

    public void getReviews(double lat, double lon, LinearLayout container, Cb<Review> callback) {
        db.collection("reviews")
                .whereEqualTo("latitude", lat)
                .whereEqualTo("longitude", lon)
                .get()
                .addOnSuccessListener(queryDocumentSnapshots -> {
                    List<Review> reviews = new ArrayList<>();
                    for (var doc : queryDocumentSnapshots.getDocuments()) {
                        Review review = doc.toObject(Review.class);
                        if (review != null) {
                            reviews.add(review);
                        }
                    }

                    reviews.sort((a, b) -> Long.compare(b.getCreatedAt(), a.getCreatedAt()));

                    for (Review review : reviews) {
                        callback.rtui(review, container);
                    }
                });
    }

    public void getBookings(double lat, double lon, LinearLayout container, Cb<Booking> callback) {
        db.collection("bookings")
                .whereEqualTo("latitude", lat)
                .whereEqualTo("longitude", lon)
                .get()
                .addOnSuccessListener(queryDocumentSnapshots -> {
                    List<Booking> bookings = new ArrayList<>();
                    for (var doc : queryDocumentSnapshots.getDocuments()) {
                        Booking booking = doc.toObject(Booking.class);
                        if (booking != null) {
                            bookings.add(booking);
                        }
                    }

                    bookings.sort((a, b) -> Long.compare(b.getDate(), a.getDate()));

                    for (Booking booking : bookings) {
                        callback.rtui(booking, container);
                    }
                });
    }

    public interface Cb<T> {
        void rtui(T item, LinearLayout linearLayout);
    }
}
