package com.adealink.weparty.share.qrcode

import androidx.fragment.app.viewModels
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.module.playmate.data.PlaymateCategoryData
import com.adealink.weparty.module.playmate.data.UserPlaymateCategoryData
import com.adealink.weparty.share.R
import com.adealink.weparty.share.databinding.DialogChooseCategoryBinding
import com.adealink.weparty.share.qrcode.adapter.CategoryItem
import com.adealink.weparty.share.qrcode.adapter.CategoryItemViewBinder
import com.adealink.weparty.share.qrcode.viewmodel.QRCodeViewModel
import com.adealink.weparty.share.viewmodel.ShareViewModelFactory

class ChooseCategoryDialog : BottomDialogFragment(R.layout.dialog_choose_category),
    CategoryItemViewBinder.CategoryChooseListener {

    private val binding by viewBinding(DialogChooseCategoryBinding::bind)

    private val qrCodeViewModel by viewModels<QRCodeViewModel>(ownerProducer = {
        parentFragment ?: this
    }, factoryProducer = { ShareViewModelFactory() })
    private val listAdapter by fastLazy { MultiTypeListAdapter<CategoryItem>() }

    private var list: List<UserPlaymateCategoryData> = emptyList()
    private var selected: UserPlaymateCategoryData? = null

    fun setCategoryList(list: List<UserPlaymateCategoryData>, selected: UserPlaymateCategoryData?) {
        this.list = list
        this.selected = selected
    }


    override fun initViews() {
        super.initViews()
        listAdapter.register(CategoryItemViewBinder(this))
        binding.rvCategory.adapter = listAdapter
        listAdapter.submitList(
            list.map { CategoryItem(it, it == selected) }
        )
    }

    override fun onChoose(data: UserPlaymateCategoryData) {
        qrCodeViewModel.selectCategory(data)
        dismiss()
    }

}