package it.czerwinski.customnavigatorexample

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.findNavController
import androidx.navigation.plusAssign

class MainActivity : AppCompatActivity() {

    private val navController get() = findNavController(R.id.navHostMain)

    private val customNavigator = ConstraintLayoutNavigator(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main) // <-- App crashes here after screen rotation if at destination R.id.animatedLayoutDestination

        // I cannot find navController before the layout is inflated:
        navController.navigatorProvider += customNavigator

        // I can only add custom destination after the custom navigator. Otherwise, app crashes.
        val customDestination = createCustomDestination()
        navController.graph.addDestination(customDestination)
    }

    private fun createCustomDestination(): ConstraintLayoutNavigator.Destination {
        val customDestination = customNavigator.createDestination()
        customDestination.id = R.id.animatedLayoutDestination
        customDestination.target = R.id.rootLayout
        customDestination.layoutRes = R.layout.fragment_changed
        return customDestination
    }

    /**
     * Overriding this method to animate layout on back button
     */
    override fun onBackPressed() {
        if (!navController.navigateUp()) super.onBackPressed()
    }
}
