package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.PurchaseOrderDTO;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.repositories.PurchaseOrderRepository;
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 PurchaseOrderListViewModel extends ViewModel {
    private final PurchaseOrderRepository purchaseOrderRepository;
    private final StoreRepository storeRepository;

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

    @Inject
    public PurchaseOrderListViewModel(PurchaseOrderRepository purchaseOrderRepository, StoreRepository storeRepository) {
        this.purchaseOrderRepository = purchaseOrderRepository;
        this.storeRepository = storeRepository;
    }

    public LiveData<List<PurchaseOrderDTO>> getPurchaseOrders() { return purchaseOrders; }
    public LiveData<List<StoreDTO>> getStores() { return stores; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }

    public void loadPurchaseOrders(String query, Long storeId) {
        isLoading.setValue(true);
        purchaseOrderRepository.getAllPurchaseOrders(0, 100, query, storeId, "purchaseOrderId,desc").observeForever(resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    purchaseOrders.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());
            }
        });
    }
}
