package com.datarecovery.master.data.repositories;

import com.atmob.common.data.KVUtils;
import com.atmob.sdk.gravity_engine.GravityEngine;
import com.datarecovery.master.data.api.V8Api;
import com.datarecovery.master.data.api.request.BaseRequest;
import com.datarecovery.master.data.api.response.AtmobUserResponse;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.RxHttpHandler;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import atmob.reactivex.rxjava3.core.Single;
import atmob.rxjava.utils.RxJavaUtil;

@Singleton
public class AdRepository {
    private static final String KEY_IS_ATTRIBUTED = "ad_repository_is_attributed";
    private final V8Api v8Api;

    @Inject
    public AdRepository(V8Api v8Api) {
        this.v8Api = v8Api;
    }

    public Single<AtmobUserResponse> getAtmobUser() {
        return v8Api.getAtmobUser(new BaseRequest())
                .compose(RxHttpHandler.handle(false))
                .doOnSuccess(atmobUserResponse -> {
                    if (atmobUserResponse.isAttributed()) {
                        KVUtils.getDefault().putBoolean(KEY_IS_ATTRIBUTED, true);
                    }
                })
                .retryWhen(RxJavaUtil.exponentialBackOff(null, 8, TimeUnit.SECONDS))
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }

    public Single<Boolean> isAttributed() {
        boolean isAttribute = KVUtils.getDefault().getBoolean(KEY_IS_ATTRIBUTED, false);
        if (isAttribute) {
            return Single.just(true);
        }
        if (BoxingUtil.boxing(GravityEngine.getAttributionStatus() == GravityEngine.ATTRIBUTED)) {
            return Single.just(true);
        }
        return getAtmobUser()
                .map(AtmobUserResponse::isAttributed)
                .map(isAttributed -> isAttributed || BoxingUtil.boxing(GravityEngine.getAttributionStatus() == GravityEngine.ATTRIBUTED))
                .doOnSuccess(isAttributed -> {
                    if (isAttributed) {
                        KVUtils.getDefault().putBoolean(KEY_IS_ATTRIBUTED, true);
                    }
                })
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }
}
