package com.develop.step

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.develop.food.base.ui.FullScreenTransparentDialog
import com.develop.food.base.utils.QRCodeUtils
import com.develop.food.base.utils.ThreadUtils
import com.develop.food.base.utils.setGone
import com.develop.step.databinding.DialogShareQrCodeBinding

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)
            }
        })
    }
}