package com.p3.bewoplaner.page.splash;

import com.p3.bewoplaner.BuildConfig;
import com.p3.bewoplaner.data.AppPrefsConstants;
import com.p3.bewoplaner.data.prefs.BooleanPreference;
import com.p3.bewoplaner.data.prefs.StringPreference;
import com.p3.bewoplaner.page.mvp.MVPAbstractPresenter;
import com.p3.bewoplaner.utils.rx.RxUtils;

import android.support.annotation.NonNull;

import java.util.concurrent.TimeUnit;

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

import rx.Subscription;

/**
 * Created by imarneanu on 2/9/17.
 */
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() {
    }

    /**
     * Start timer for splash screen.
     */

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

    /**
     * Check if the user is already logged in and saved the passwords.
     */
    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);
    }
}
