package de.sebse.fuplanner.tools;

import java.util.LinkedList;

import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;

public class NewAsyncQueue {
    private final LinkedList<AsyncQueueCallback> mQueue = new LinkedList<>();
    private boolean mIsRunning = false;

    public void add(AsyncQueueCallback callback) {
        if (isRunning())
            getQueue().addLast(callback);
        else {
            setRunning(true);
            callback.run();
        }
    }

    public void next() {
        AsyncQueueCallback callback = getQueue().pollFirst();
        if (callback == null)
            setRunning(false);
        else
            callback.run();
    }

    public interface AsyncQueueCallback {
        void run();
    }

    public NetworkErrorCallback check(NetworkErrorCallback value) {
        return error -> {
            value.onError(error);
            next();
        };
    }

    public <T> NetworkCallback<T> check(NetworkCallback<T> value) {
        return success -> {
            value.onResponse(success);
            next();
        };
    }

    private boolean isRunning() {
        return mIsRunning;
    }

    private void setRunning(boolean value) {
        mIsRunning = value;
    }

    private LinkedList<AsyncQueueCallback> getQueue() {
        return mQueue;
    }
}
