package com.seatel.mobilehall.ui.lang.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.FragmentLanguageBinding
import com.seatel.mobilehall.ui.application.MyApplication
import com.seatel.mobilehall.ui.lang.adapter.LanguageAdapter
import com.seatel.mobilehall.ui.lang.interactor.SettingLanguageInteractor
import com.seatel.mobilehall.ui.lang.model.LanguageModel
import com.seatel.mobilehall.ui.login.fragment.LoginFragment
import com.seatel.mobilehall.ui.login.fragment.MainFragment
import com.seatel.mobilehall.util.lang.LanguageManager

class LanguageFragment : MainFragment(), SettingLanguageInteractor {

    private var mSettingLanguageInteractor: SettingLanguageInteractor? = null
    private var _binding: FragmentLanguageBinding? = null
    private val binding get() = _binding!!

    private fun setSettingLanguageInteractor(mSettingLanguageInteractor: SettingLanguageInteractor) {
        this.mSettingLanguageInteractor = mSettingLanguageInteractor
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_language)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentLanguageBinding.bind(view)  // Inflate the binding
        init()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null  // Clean up binding when view is destroyed
    }

    override fun onBackPress() {
        super.onBackPress()
        getMainActivity().activityExitFadeOutAnimation()
        getMainActivity().finish()
    }

    private fun showScreenLogin() {
        getmMainFragmentPresenter()!!.addFragment(LoginFragment(), true)
    }

    private fun init() {
        setSettingLanguageInteractor(this)
        binding.rlvLanguage.layoutManager = LinearLayoutManager(context)
        binding.rlvLanguage.adapter =
            LanguageAdapter(requireContext(), mSettingLanguageInteractor)
    }

    override fun onItemLanguageDataClick(languageModel: LanguageModel?) {
        showScreenLogin()
        MyApplication.isFirstInstall = true
        languageModel?.let {
            LanguageManager.getInstance(requireContext())
                .setSelectedLanguage(it.languageCode!!)
        }
    }
}
