package com.develop.common.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.develop.base.ext.setGone
import com.develop.base.mvvm.FullScreenTransparentDialog
import com.develop.base.util.ThreadUtils
import com.develop.common.databinding.DialogShareQrCodeBinding
import com.develop.common.utils.QRCodeUtils

class ShareQRCodeDialog : FullScreenTransparentDialog() {

    private lateinit var binding: DialogShareQrCodeBinding
    var recipeNum: String = ""
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DialogShareQrCodeBinding.inflate(inflater, container, false)
        binding.ivQrCode.viewTreeObserver.addOnPreDrawListener(
            object : ViewTreeObserver.OnPreDrawListener {
                override fun onPreDraw(): Boolean {
                    binding.ivQrCode.viewTreeObserver.removeOnPreDrawListener(this)
                    loadQRCode(binding.ivQrCode.width, binding.ivQrCode.height)
                    return false
                }
            })
        binding.ivCancel.setOnClickListener {
            removeSelf()
        }
        return binding.root
    }

    private fun loadQRCode(width: Int, height: Int) {
        ThreadUtils.runOnWorkThread({
            val bitmap = QRCodeUtils.createQRCodeBitmap(recipeNum, width, height)
            binding.ivQrCode.post {
                binding.loading.setGone()
                binding.ivQrCode.setImageBitmap(bitmap)
            }
        })
    }
}