package com.adealink.weparty.share.qrcode.page.special

import androidx.fragment.app.viewModels
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.module.playmate.data.UserPlaymateCategoryData
import com.adealink.weparty.share.R
import com.adealink.weparty.share.qrcode.QRCodeShareDialog
import com.adealink.weparty.share.qrcode.page.special.viewmodel.SpecialQRCodePage
import com.adealink.weparty.share.qrcode.page.special.viewmodel.SpecialQRCodeViewModel
import com.adealink.weparty.share.qrcode.viewmodel.QRCodeViewModel
import com.adealink.weparty.viewmodel.parentFragmentViewModels

class SpecialQRCodeFragment : BaseFragment(R.layout.fragment_special_qr_code) {


    private val qrCodeViewModel by parentFragmentViewModels<QRCodeViewModel, QRCodeShareDialog>(
        QRCodeShareDialog::class.java
    )
    private val specialQRCodeViewModel by viewModels<SpecialQRCodeViewModel>()

    private var currentCategory: UserPlaymateCategoryData? = null
    private var stepPage: SpecialQRCodePage? = null

    override fun initViews() {
        super.initViews()
        inflatePage(SpecialQRCodePage.STEP_1)
    }

    private fun inflatePage(page: SpecialQRCodePage) {
        if (stepPage == page) {
            return
        }
        stepPage = page
        when (stepPage) {
            SpecialQRCodePage.STEP_2 -> {
                childFragmentManager.beginTransaction()
                    .replace(R.id.fv_content, SpecialQRCodeStep2Fragment(), "PAGE_STEP_2")
                    .commitAllowingStateLoss()
            }

            else -> {
                childFragmentManager.beginTransaction()
                    .replace(R.id.fv_content, SpecialQRCodeStep1Fragment(), "PAGE_STEP_1")
                    .commitAllowingStateLoss()
            }
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        qrCodeViewModel.currentCategoryLD.observe(this) { data ->
            if (currentCategory?.id == data?.id) {
                return@observe
            }
            currentCategory = data
            inflatePage(SpecialQRCodePage.STEP_1)
        }
        specialQRCodeViewModel.pageLD.observeWithoutCache(this) {
            inflatePage(it)
        }
    }


}