package com.adealink.weparty.joinus.step2.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.frame.mvvm.viewmodel.viewModels
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.joinus.databinding.LayoutJoinUsStep2EditLanguageBinding
import com.adealink.weparty.joinus.step2.data.LanguageConfigData
import com.adealink.weparty.joinus.step2.dialog.ChooseLanguageDialog
import com.adealink.weparty.joinus.step2.viewmodel.Step2ViewModel
import com.adealink.weparty.joinus.viewmodel.JoinUsViewModelFactory

class EditLanguageComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutJoinUsStep2EditLanguageBinding
) : BaseViewComponent(lifecycleOwner) {

    companion object {
        private const val TAG = "EditLanguageComp"
    }

    private val editViewModel by viewModels<Step2ViewModel> { JoinUsViewModelFactory() }

    override fun initViews() {
        super.initViews()
        binding.clLanguage.onClick {
            showLanguageDialog()
        }
    }

    override fun observeViewModel() {
        editViewModel.editUserInfoLD.observe(viewLifecycleOwner) {
            updateUI(it.languages)
        }
    }

    private fun updateUI(languages: List<LanguageConfigData>?) {
        if (languages.isNullOrEmpty()) {
            binding.tvLanguage.text = null
            return
        }
        binding.tvLanguage.text = languages.joinToString(separator = ",") { it.name }
    }

    private fun showLanguageDialog() {
        ChooseLanguageDialog().apply {
            setLanguageItemList(editViewModel.editUserInfoLD.value?.languages)
            setChooseCallback { list ->
                editViewModel.setLanguage(list)
            }
        }.show(fragmentManager, "ChooseLanguageDialog")
    }

}