package net.squanchy.contest;

import net.squanchy.remoteconfig.RemoteConfig;
import net.squanchy.service.firebase.FirebaseAuthService;
import net.squanchy.service.firebase.FirebaseDbService;
import net.squanchy.service.firebase.model.FirebaseAchievements;

import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;

public class ContestService {

    private final RemoteConfig remoteConfig;
    private final FirebaseDbService dbService;
    private final FirebaseAuthService authService;

    public ContestService(RemoteConfig remoteConfig, FirebaseDbService dbService, FirebaseAuthService authService) {
        this.remoteConfig = remoteConfig;
        this.dbService = dbService;
        this.authService = authService;
    }

    public Single<ContestStandings> standings() {
        return authService.ifUserSignedInThenObservableFrom(dbService::achievements)
                .first(FirebaseAchievements.empty())
                .zipWith(remoteConfig.contestGoal(), buildStandings())
                .subscribeOn(Schedulers.io());
    }

    private BiFunction<FirebaseAchievements, Integer, ContestStandings> buildStandings() {
        return (achievements, goal) -> ContestStandings.create(goal, achievements.achievements.size(), "");
    }
    
}

@@ -251,16 +251,121 @@
 ments;%0A%0A
+import io.fabric.sdk.android.services.common.SystemCurrentTimeProvider;%0Aimport io.reactivex.Completable;%0A
 import i
@@ -1437,15 +1437,315 @@
 ;%0A    %7D%0A
+%0A
     
+public Single%3CContestStandings%3E addAchievement(String checkpointId) %7B%0A        return authService.ifUserSignedInThenCompletableFrom(%0A                userId -%3E dbService.addAchievement(checkpointId, userId, System.currentTimeMillis())%0A        ).andThen(standings()).subscribeOn(Schedulers.io());%0A    %7D
 %0A%7D%0A

add achievements and then return standings