package de.sebse.fuplanner.services.KVV;

import android.content.Context;

import org.json.JSONException;
import org.json.JSONObject;

import de.sebse.fuplanner.services.KVV.types.LoginToken;
import de.sebse.fuplanner.tools.network.HTTPService;
import de.sebse.fuplanner.tools.network.NetworkCallback;
import de.sebse.fuplanner.tools.network.NetworkError;
import de.sebse.fuplanner.tools.network.NetworkErrorCallback;

final class TestLogin extends HTTPService {

    private TestLogin(Context context) {
        super(context);
    }

    static void testLogin(Context context, LoginToken loginToken, NetworkCallback<LoginToken> callback, NetworkErrorCallback errorCallback) {
        new TestLogin(context).get(String.format("https://kvv.imp.fu-berlin.de/direct/profile/%s.json", loginToken.getUsername()), loginToken.getCookies(), response -> {
            String body = response.getParsed();
            try {
                JSONObject json = new JSONObject(body);
                String displayName = json.getString("displayName");
                String email = json.getString("email");
                loginToken.setAdditionals(displayName, email);
                callback.onResponse(loginToken);
            } catch (JSONException e) {
                errorCallback.onError(new NetworkError(100201, 403, "Cannot parse profile!"));
            }
        }, error -> errorCallback.onError(new NetworkError(100200, error.networkResponse.statusCode, "Testing login failed!")));
    }
}
