package de.sebse.fuplanner.services.kvv;

import android.content.Context;
import android.util.Pair;

import java.util.concurrent.atomic.AtomicReference;

import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;

final public class ModulesDetails extends Part<Pair<Modules.Module, Boolean>> {
    private final PartModules[] parts;

    ModulesDetails(Login login, ModulesList list, Context context, PartModules[] parts) {
        super(login, list, context);
        this.parts = parts;
    }

    @Override
    protected void recv(final Modules.Module module, final NetworkCallback<Pair<Modules.Module, Boolean>> callback, final NetworkErrorCallback errorCallback, final boolean forceRefresh, final int retries) {
        final int[] returned = {0};
        AtomicReference<NetworkError> lastError = new AtomicReference<>(null);
        NetworkCallback<Modules.Module> successCb = success -> {
            returned[0] += 1;
            callback.onResponse(Pair.create(module, false));
            if (returned[0] == parts.length) {
                callback.onResponse(Pair.create(module, true));
                if (lastError.get() != null)
                    errorCallback.onError(lastError.get());
            }
        };
        NetworkErrorCallback errorCb = error -> {
            lastError.set(error);
            returned[0] += 1;
            if (returned[0] == parts.length) {
                callback.onResponse(Pair.create(module, true));
                if (lastError.get() != null)
                    errorCallback.onError(lastError.get());
            }
        };
        for (PartModules<?> part: parts) {
            part.recv(module, successCb, errorCb, forceRefresh, RETRY_COUNT);
        }
    }
}
