package de.beyondsoft.ownchat.page.splash;

import de.beyondsoft.ownchat.BuildConfig;
import de.beyondsoft.ownchat.data.AppPrefsConstants;
import de.beyondsoft.ownchat.data.prefs.BooleanPreference;
import de.beyondsoft.ownchat.data.prefs.StringPreference;
import de.beyondsoft.ownchat.page.mvp.MVPAbstractPresenter;
import de.beyondsoft.ownchat.utils.rx.RxUtils;

import android.support.annotation.NonNull;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Named;

import rx.Subscription;

class SplashPresenter extends MVPAbstractPresenter<SplashView> implements SplashView.Callbacks {

    private static final int SPLASH_DELAY_MILLIS = BuildConfig.DEBUG ? 0 : 1500;

    @Inject
    @Named(AppPrefsConstants.LOGIN_TOKEN)
    StringPreference mLoginTokenPreference;

    @Inject
    @Named(AppPrefsConstants.SAVE_PASSWORD)
    BooleanPreference mSavePasswordPreference;

    @Inject
    SplashPresenter() {
    }

    @Override
    public void startTimer() {
        Subscription subscription = rx.Observable.timer(0, TimeUnit.MILLISECONDS)
                .compose(RxUtils.provideDefaultTransformer())
                .subscribe(aLong -> checkUserLoggedIn());
        addSubscription(subscription);
    }

    private void checkUserLoggedIn() {
        getView().userLoggedIn(mLoginTokenPreference.isSet() && mSavePasswordPreference.get());
    }

    @Override
    protected void afterAttachView(@NonNull SplashView view) {
        super.afterAttachView(view);
        view.setCallbacks(this);
    }

    @Override
    protected void beforeDetachView(@NonNull SplashView view) {
        view.setCallbacks(null);
        super.beforeDetachView(view);
    }
}
