package it.integry.integrywmsnative.core.data_store.db.respository_new;

import android.os.Handler;

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

import java.util.List;

import javax.inject.Inject;

import io.reactivex.rxjava3.schedulers.Schedulers;
import it.integry.integrywmsnative.core.data_store.db.entity.InventarioRowRoomDTO;
import it.integry.integrywmsnative.core.data_store.db.respository_new.data_source.InventarioRowLocalDataSource;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.mapper.InventarioRowMapper;
import it.integry.integrywmsnative.core.model.MtbInvenr;
import it.integry.integrywmsnative.core.rest.consumers.InventarioRESTConsumer;

public class InventarioRowRepository extends _BaseRepository<MtbInvenr, InventarioRowRoomDTO, InventarioRowMapper, InventarioRowLocalDataSource, InventarioRESTConsumer> {

    private final Handler handler;
    private final MutableLiveData<List<InventarioRowRoomDTO>> internalLiveData = new MutableLiveData<>();

    @Inject
    public InventarioRowRepository(InventarioRowLocalDataSource localDataSource,
                                   InventarioRESTConsumer remoteDataSource,
                                   InventarioRowMapper dataMapper,
                                   Handler handler) {
        super(dataMapper, localDataSource, remoteDataSource);
        this.handler = handler;
    }


    public LiveData<List<InventarioRowRoomDTO>> retrieve(long parentId) {
        localDataSource.makeSynchronousRetrieveAllLive(parentId, true, false)
                .observeOn(Schedulers.io())
                .subscribe(internalLiveData::postValue);
//        refresh(onComplete, onError);

        return internalLiveData;
    }


    public void insert(InventarioRowRoomDTO inventarioRowDTO, Runnable onComplete, RunnableArgs<Exception> onError) {
        localDataSource.makeInsertRequest(inventarioRowDTO, localResult -> {
            if (onComplete != null) handler.post(onComplete);
        }, onError);
    }


    public void delete(InventarioRowRoomDTO inventarioRowDTO, Runnable onComplete, RunnableArgs<Exception> onError) {
        localDataSource.makeDeleteRequest(inventarioRowDTO, onComplete, onError);
    }


    public void update(InventarioRowRoomDTO inventarioRowDTO, Runnable onComplete, RunnableArgs<Exception> onError) {
        inventarioRowDTO.setRemoteSyncDate(null);

        localDataSource.makeUpdateRequest(inventarioRowDTO, localResult -> {
            if (onComplete != null) handler.post(onComplete);
        }, onError);
    }
}
