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.SupplierDTO;
import com.example.petstoremobile.repositories.SupplierRepository;
import com.example.petstoremobile.utils.Resource;

import androidx.lifecycle.Observer;

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

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class SupplierListViewModel extends ViewModel {
    private final SupplierRepository repository;

    private final MutableLiveData<List<SupplierDTO>> suppliers = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);

    @Inject
    public SupplierListViewModel(SupplierRepository repository) {
        this.repository = repository;
    }

    public LiveData<List<SupplierDTO>> getSuppliers() { return suppliers; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }

    public void loadSuppliers(String query) {
        isLoading.setValue(true);
        observeOnce(repository.getAllSuppliers(0, 100, query, "supCompany"), resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    suppliers.setValue(resource.data.getContent());
                    isLoading.setValue(false);
                } else if (resource.status == Resource.Status.ERROR) {
                    isLoading.setValue(false);
                }
            }
        });
    }

    private <T> void observeOnce(LiveData<Resource<T>> liveData, Observer<Resource<T>> handler) {
        liveData.observeForever(new Observer<Resource<T>>() {
            @Override
            public void onChanged(Resource<T> resource) {
                if (resource == null || resource.status != Resource.Status.LOADING) {
                    liveData.removeObserver(this);
                }
                handler.onChanged(resource);
            }
        });
    }

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