package kr.co.vividnext.sodalive.message

import android.os.Bundle
import android.view.View
import com.google.android.material.tabs.TabLayout
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.base.BaseFragment
import kr.co.vividnext.sodalive.databinding.FragmentMessageBinding
import kr.co.vividnext.sodalive.message.text.TextMessageFragment
import kr.co.vividnext.sodalive.message.voice.VoiceMessageFragment

class MessageFragment : BaseFragment<FragmentMessageBinding>(FragmentMessageBinding::inflate) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupView()
        changeFragment("message")
    }

    private fun setupView() {
        val tabs = binding.tabs
        tabs.addTab(tabs.newTab().setText("문자").setTag("message"))
        tabs.addTab(tabs.newTab().setText("음성").setTag("voice"))

        tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val tag = tab.tag as String
                changeFragment(tag)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
            }
        })
    }

    private fun changeFragment(tag: String) {
        val fragmentManager = childFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()

        val currentFragment = fragmentManager.primaryNavigationFragment
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment)
        }

        var fragment = fragmentManager.findFragmentByTag(tag)
        if (fragment == null) {
            fragment = if (tag == "message") {
                TextMessageFragment()
            } else {
                VoiceMessageFragment()
            }

            fragmentTransaction.add(R.id.container, fragment, tag)
        } else {
            fragmentTransaction.show(fragment)
        }

        fragmentTransaction.setPrimaryNavigationFragment(fragment)
        fragmentTransaction.setReorderingAllowed(true)
        fragmentTransaction.commitNow()
    }
}
