package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.BulkDeleteRequest;
import com.example.petstoremobile.dtos.PageResponse;
import com.example.petstoremobile.dtos.PetDTO;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.repositories.PetRepository;
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 PetListViewModel extends ViewModel {
    private final PetRepository petRepository;
    private final StoreRepository storeRepository;

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

    @Inject
    public PetListViewModel(PetRepository petRepository, StoreRepository storeRepository) {
        this.petRepository = petRepository;
        this.storeRepository = storeRepository;
    }

    public LiveData<List<PetDTO>> getPets() { return pets; }
    public LiveData<List<StoreDTO>> getStores() { return stores; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }

    public void loadPets(String query, String status, String species, Long storeId) {
        if ("All Statuses".equals(status)) status = null;
        if ("All Species".equals(species)) species = null;

        isLoading.setValue(true);
        petRepository.getAllPets(0, 100, query, status, species, storeId, null, "petName").observeForever(resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    pets.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>> bulkDeletePets(List<String> ids) {
        return petRepository.bulkDeletePets(new BulkDeleteRequest(ids));
    }
}
