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.Date;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.rxjava3.schedulers.Schedulers;
import it.integry.integrywmsnative.core.data_store.db.entity.InventarioRoomDTO;
import it.integry.integrywmsnative.core.data_store.db.respository_new.data_source.InventarioLocalDataSource;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.mapper.InventarioMapper;
import it.integry.integrywmsnative.core.model.MtbInvent;
import it.integry.integrywmsnative.core.rest.consumers.InventarioRESTConsumer;

public class InventarioRepository extends _BaseRepository<MtbInvent, InventarioRoomDTO, InventarioMapper, InventarioLocalDataSource, InventarioRESTConsumer> {

    private final Handler handler;

    private final MutableLiveData<List<InventarioRoomDTO>> internalLiveData = new MutableLiveData<>();

    @Inject
    public InventarioRepository(InventarioLocalDataSource localDataSource,
                                InventarioRESTConsumer remoteDataSource,
                                InventarioMapper dataMapper,
                                Handler handler) {
        super(dataMapper, localDataSource, remoteDataSource);
        this.handler = handler;
    }


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

        return internalLiveData;
    }


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

    public void export(InventarioRoomDTO inventarioDTO, Runnable onComplete, RunnableArgs<Exception> onError) {
        remoteDataSource.makeInsertRequest(dataMapper.mapRoomToRest(inventarioDTO), () -> {
            inventarioDTO.setRemoteSyncDate(new Date());

            localDataSource.makeUpdateRequest(inventarioDTO, (ignored) -> {
                handler.post(onComplete);
            }, onError);
        }, onError);
    }

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

}
