package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.CategoryDTO;
import com.example.petstoremobile.dtos.DropdownDTO;
import com.example.petstoremobile.dtos.PageResponse;
import com.example.petstoremobile.dtos.ProductDTO;
import com.example.petstoremobile.repositories.CategoryRepository;
import com.example.petstoremobile.repositories.ProductRepository;
import com.example.petstoremobile.utils.Resource;

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

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;
import okhttp3.MultipartBody;

@HiltViewModel
public class ProductDetailViewModel extends ViewModel {
    private final ProductRepository productRepository;
    private final CategoryRepository categoryRepository;

    private final MutableLiveData<List<DropdownDTO>> categoryList = new MutableLiveData<>(new ArrayList<>());
    private long prodId = -1;
    private boolean isEditing = false;

    @Inject
    public ProductDetailViewModel(ProductRepository productRepository, CategoryRepository categoryRepository) {
        this.productRepository = productRepository;
        this.categoryRepository = categoryRepository;
    }

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

    public long getProdId() {
        return prodId;
    }

    public boolean isEditing() {
        return isEditing;
    }

    public LiveData<Resource<List<DropdownDTO>>> loadCategories() {
        return productRepository.getCategoryDropdowns();
    }

    public LiveData<Resource<ProductDTO>> loadProduct() {
        return productRepository.getProductById(prodId);
    }

    public LiveData<Resource<ProductDTO>> saveProduct(ProductDTO dto) {
        if (isEditing) {
            return productRepository.updateProduct(prodId, dto);
        } else {
            return productRepository.createProduct(dto);
        }
    }

    public LiveData<Resource<Void>> deleteProduct() {
        return productRepository.deleteProduct(prodId);
    }

    public LiveData<Resource<Void>> uploadProductImage(MultipartBody.Part image) {
        return productRepository.uploadProductImage(prodId, image);
    }

    public LiveData<Resource<Void>> deleteProductImage() {
        return productRepository.deleteProductImage(prodId);
    }

    public void setCategoryList(List<DropdownDTO> list) {
        categoryList.setValue(list);
    }

    public LiveData<List<DropdownDTO>> getCategoryList() {
        return categoryList;
    }
}

