package com.example.petstoremobile.viewmodels;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.petstoremobile.dtos.AppointmentDTO;
import com.example.petstoremobile.dtos.BulkDeleteRequest;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.repositories.AppointmentRepository;
import com.example.petstoremobile.repositories.StoreRepository;
import com.example.petstoremobile.utils.Resource;

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

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class AppointmentListViewModel extends ViewModel {
    private final AppointmentRepository appointmentRepository;
    private final StoreRepository storeRepository;

    private final MutableLiveData<List<AppointmentDTO>> appointments = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<StoreDTO>> stores = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);

    @Inject
    public AppointmentListViewModel(AppointmentRepository appointmentRepository, StoreRepository storeRepository) {
        this.appointmentRepository = appointmentRepository;
        this.storeRepository = storeRepository;
    }

    public LiveData<List<AppointmentDTO>> getAppointments() { return appointments; }
    public LiveData<List<StoreDTO>> getStores() { return stores; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }

    public void loadAppointments(String query, String status, Long storeId, String date, Long employeeId) {
        isLoading.setValue(true);
        appointmentRepository.getAllAppointments(0, 500, query, status, storeId, date, employeeId).observeForever(resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    appointments.setValue(resource.data.getContent());
                    isLoading.setValue(false);
                } else if (resource.status == Resource.Status.ERROR) {
                    isLoading.setValue(false);
                }
            }
        });
    }

    public void loadStores() {
        storeRepository.getAllStores(0, 100).observeForever(resource -> {
            if (resource != null && resource.status == Resource.Status.SUCCESS && resource.data != null) {
                stores.setValue(resource.data.getContent());
            }
        });
    }

    public LiveData<Resource<Void>> bulkDeleteAppointments(List<String> ids) {
        return appointmentRepository.bulkDeleteAppointments(new BulkDeleteRequest(ids));
    }
}
