package com.mobiuz.app.dev.ui.settings

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentLanguageBinding
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.base.BaseFragment
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.utils.LocaleHelper
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject


@AndroidEntryPoint
class LanguageFragment : BaseFragment(R.layout.fragment_language) {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: FragmentLanguageBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentLanguageBinding.bind(view)
        setUpUI()
        collects()

    }

    override fun setUpUI() {
        bn.apply {
            toolbar.setNavigationOnClickListener {
                requireActivity().finish()
            }
            bn.apply {
                when (pref.language) {
                    CONSTANTS.UZ -> imageUzbek.isVisible = true
                    CONSTANTS.RU -> imageRussian.isVisible = true
                    CONSTANTS.EN -> imageEnglish.isVisible = true
                }
                uzbekLang.setOnClickListener(object : ButtonClick(){
                    override fun onSingleClick(v: View?) {
                        setLangAndNavigate(CONSTANTS.UZ)
                    }
                })

                russianLang.setOnClickListener(object : ButtonClick(){
                    override fun onSingleClick(v: View?) {
                        setLangAndNavigate(CONSTANTS.RU)
                    }
                })

                englishLang.setOnClickListener(object : ButtonClick(){
                    override fun onSingleClick(v: View?) {
                        setLangAndNavigate(CONSTANTS.EN)
                    }
                })

            }


        }
    }

    private fun setLangAndNavigate(lang: String) {
        pref.language = lang
        LocaleHelper.setLocale(requireContext())
        val intent = Intent(requireContext(), SettingsActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        startActivity(intent)
        requireActivity().finish()
    }

    override fun collects() {
    }


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