package it.integry.integrywmsnative.core.data_store.db.repository.datasource;

import android.os.Handler;

import java.util.concurrent.ExecutorService;

import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.expansion.RunnableWithReturn;

public class BaseDataSource {

    protected final ExecutorService executorService;
    protected final Handler handler;

    protected BaseDataSource(ExecutorService executorService, Handler handler) {
        this.executorService = executorService;
        this.handler = handler;
    }

    protected <T> void execute(RunnableWithReturn<T> query, RunnableArgs<T> onSuccess, RunnableArgs<Exception> onError) {
        executorService.execute(() -> {
            try {
                var data = query.run();
                handler.post(() -> onSuccess.run(data));
            } catch (Exception ex) {
                handler.post(() -> onError.run(ex));
            }
        });
    }

    protected void execute(Runnable query, Runnable onSuccess, RunnableArgs<Exception> onError) {
        executorService.execute(() -> {
            try {
                query.run();
                handler.post(onSuccess);
            } catch (Exception ex) {
                handler.post(() -> onError.run(ex));
            }
        });
    }
}
