package dominando.android.livros

import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.google.firebase.auth.FirebaseAuth

abstract class BaseFragment : Fragment() {
    private val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance()
    private var authListener: FirebaseAuth.AuthStateListener =
            FirebaseAuth.AuthStateListener {
                if (it.currentUser != null) {
                    init()
                } else {
                    goToLogin()
                }
            }

    val navController: NavController
        get() = Navigation.findNavController(requireActivity(), R.id.navHost)

    override fun onStart() {
        super.onStart()
        firebaseAuth.addAuthStateListener(authListener)
    }

    override fun onStop() {
        super.onStop()
        firebaseAuth.removeAuthStateListener(authListener)
    }

    protected abstract fun init()

    private fun goToLogin() {
        requireActivity().finish()
        val it = Intent(requireContext(), SignInActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        }
        startActivity(it)
    }
}
