package ru.myitschool.work.ui.splash

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import ru.myitschool.work.R
import ru.myitschool.work.databinding.FragmentSplashBinding
import ru.myitschool.work.ui.login.LoginDestination
import ru.myitschool.work.ui.profile.ProfileDestination
import ru.myitschool.work.utils.collectWhenStarted

@AndroidEntryPoint
class SplashFragment : Fragment(R.layout.fragment_splash) {
    private var _binding: FragmentSplashBinding? = null
    private val binding: FragmentSplashBinding get() = _binding!!

    private val viewModel: SplashViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentSplashBinding.bind(view)
        subscribe()
    }

    private fun subscribe() {
        viewModel.action.collectWhenStarted(this) { action ->
            when (action) {
                SplashViewModel.Action.OpenProfile -> {
                    findNavController().navigate(ProfileDestination) {
                        popUpTo(SplashDestination) { inclusive = true }
                    }
                }

                SplashViewModel.Action.OpenLogin -> {
                    findNavController().navigate(LoginDestination) {
                        popUpTo<SplashDestination> { inclusive = true }
                    }
                }
            }
        }
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}