package com.iotize.plugin.cordova.zebrarfid;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.core.os.HandlerCompat;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PluginTaskHelper {

    private static final String TAG = "PluginTaskHelper";
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Handler mainThreadHandler = HandlerCompat.createAsync(Looper.getMainLooper());


    public  <DataType, ErrorType extends Throwable> void  async(AsyncMethodCallback<DataType, ErrorType> asyncMethodCallback) {
        executorService.execute(() -> {
            try {
                final DataType result = asyncMethodCallback.doInBackground();
                mainThreadHandler.post(() -> {
                    try {
                        asyncMethodCallback.onComplete(result);
                    }
                    catch (Throwable err) {
                        try {
                            asyncMethodCallback.onError(err);
                        } catch (Exception e) {
                            Log.d(TAG, "unexpected error", err);
                        }
                    }
                });
            } catch (Throwable e) {
                mainThreadHandler.post(() -> {
                    try {
                        asyncMethodCallback.onError(e);
                    }
                    catch (Throwable err) {
                        Log.d(TAG, "unexpected error", err);
                    }
                });
            }
        });
    }

}
