package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.DropdownDTO;
import com.example.petstoremobile.dtos.InventoryDTO;
import com.example.petstoremobile.dtos.PageResponse;
import com.example.petstoremobile.dtos.ProductDTO;
import com.example.petstoremobile.repositories.InventoryRepository;
import com.example.petstoremobile.repositories.ProductRepository;
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 InventoryDetailViewModel extends ViewModel {
    private final InventoryRepository inventoryRepository;
    private final StoreRepository storeRepository;
    private final ProductRepository productRepository;

    private long inventoryId = -1;
    private boolean isEditing = false;

    private final MutableLiveData<List<DropdownDTO>> storeList = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<DropdownDTO>> productList = new MutableLiveData<>(new ArrayList<>());

    @Inject
    public InventoryDetailViewModel(InventoryRepository inventoryRepository, StoreRepository storeRepository, ProductRepository productRepository) {
        this.inventoryRepository = inventoryRepository;
        this.storeRepository = storeRepository;
        this.productRepository = productRepository;
    }

    public void setInventoryId(long id) {
        this.inventoryId = id;
        this.isEditing = id != -1;
    }

    public long getInventoryId() { return inventoryId; }
    public boolean isEditing() { return isEditing; }

    public LiveData<Resource<InventoryDTO>> loadInventory() {
        return inventoryRepository.getInventoryById(inventoryId);
    }

    public LiveData<Resource<List<DropdownDTO>>> loadStores() {
        return storeRepository.getStoreDropdowns();
    }

    public LiveData<Resource<List<DropdownDTO>>> loadProducts() {
        return productRepository.getProductDropdowns();
    }

    public LiveData<Resource<InventoryDTO>> saveInventory(InventoryDTO dto) {
        if (isEditing) {
            return inventoryRepository.updateInventory(inventoryId, dto);
        } else {
            return inventoryRepository.createInventory(dto);
        }
    }

    public LiveData<Resource<Void>> deleteInventory() {
        return inventoryRepository.deleteInventory(inventoryId);
    }

    public void setStoreList(List<DropdownDTO> list) { storeList.setValue(list); }
    public LiveData<List<DropdownDTO>> getStoreList() { return storeList; }

    public void setProductList(List<DropdownDTO> list) { productList.setValue(list); }
    public LiveData<List<DropdownDTO>> getProductList() { return productList; }
}
