package com.mobiuz.app.dev.ui.auth

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.google.firebase.FirebaseApp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.messaging.FirebaseMessaging
import com.mobiuz.app.R
import com.mobiuz.app.databinding.ActivityAuthBinding
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.utils.Utils
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class AuthActivity : AppCompatActivity() {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: ActivityAuthBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private lateinit var navController: NavController
    private lateinit var mFirebaseAnalytics: FirebaseAnalytics

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _bn = ActivityAuthBinding.inflate(layoutInflater)
        setContentView(bn.root)
        val fragment = supportFragmentManager.findFragmentById(R.id.auth_container) as NavHostFragment
        navController = NavHostFragment.findNavController(fragment)
        FirebaseApp.initializeApp(this)
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this)


//        Firebase.messaging.subscribeToTopic("just").addOnCompleteListener { task ->
//            Log.e("AAA", "subscribe: ${task.isSuccessful}")
//        }

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if (it.isSuccessful) pref.setDeviceToken(it.result.toString())
        }
        window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        intent?.let {
            val type = it.getStringExtra(CONSTANTS.TYPE_AUTH)
            if (type == CONSTANTS.PIN_CODE) {
                navController.popBackStack()
                navController.navigate(R.id.pinFragment, null, Utils.navOptions())
            }else if (type == CONSTANTS.LOGIN) {
                val phone = it.getStringExtra(CONSTANTS.PHONE)
                navController.popBackStack()
                navController.navigate(R.id.loginFragment, bundleOf(CONSTANTS.PHONE to phone ), Utils.navOptions())
            }else if (type == CONSTANTS.TYPE_VERIFICATION) {
                val phone = it.getStringExtra(CONSTANTS.PHONE)
                navController.popBackStack()
                navController.navigate(R.id.myVerificationFragment, bundleOf(CONSTANTS.PHONE to phone ), Utils.navOptions())
            }
        }
    }

    override fun onDestroy() {
        _bn = null
        super.onDestroy()
    }
}