package de.beyondsoft.ownchat.page.splash;

import de.beyondsoft.ownchat.di.InjectionHelper;
import de.beyondsoft.ownchat.page.login.LoginActivity;
import de.beyondsoft.ownchat.page.main.MainActivity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import javax.inject.Inject;

public class SplashActivity extends AppCompatActivity implements SplashView {

    @Inject
    SplashPresenter mSplashPresenter;

    private SplashView.Callbacks mCallbacks;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            // Activity was brought to front and not created,
            // Thus finishing this will get us to the last viewed activity
            finish();
            Log.e("Splash", "FINISH");
            return;
        }

        InjectionHelper.getSplashComponent(this).inject(this);
        mSplashPresenter.attachView(this);
        mCallbacks.startTimer();
    }

    @Override
    protected void onDestroy() {
        if(mSplashPresenter != null && mSplashPresenter.isAttached()) {
            mSplashPresenter.detachView();
        }

        InjectionHelper.destroySplashComponent();
        super.onDestroy();
    }

    private void goToMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void goToLoginActivity() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    @Override
    public void userLoggedIn(boolean isUserLoggedIn) {
        if(isUserLoggedIn) {
            goToMainActivity();
            return;
        }

        goToLoginActivity();
    }

    @Override
    public void setCallbacks(Callbacks callbacks) {
        mCallbacks = callbacks;
    }
}