package com.narutohuo.xindazhou.qrcode.ui

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment

/**
 * 用于桥接 ActivityResultLauncher 的透明 Fragment
 * 
 * 这个 Fragment 不显示任何 UI，只用于处理 Activity Result
 */
class QRCodeScanFragment : Fragment() {
    
    private var launcher: ActivityResultLauncher<Intent>? = null
    private var callback: ((String?) -> Unit)? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            val data = result.data
            val scanResult = if (result.resultCode == android.app.Activity.RESULT_OK && data != null) {
                data.getStringExtra(QRCodeScanActivity.EXTRA_RESULT)
            } else {
                null
            }
            callback?.invoke(scanResult)
            // 使用完后移除 Fragment
            parentFragmentManager.beginTransaction().remove(this).commit()
        }
    }
    
    fun startScan(intent: Intent, callback: (String?) -> Unit) {
        this.callback = callback
        launcher?.launch(intent)
    }
    
    companion object {
        private const val TAG = "QRCodeScanFragment"
        
        /**
         * 在 Activity 中添加 Fragment 并启动扫码
         */
        fun startScan(activity: androidx.fragment.app.FragmentActivity, callback: (String?) -> Unit) {
            val fragment = QRCodeScanFragment()
            activity.supportFragmentManager.beginTransaction()
                .add(fragment, TAG)
                .commitNow()
            
            val intent = Intent(activity, QRCodeScanActivity::class.java)
            fragment.startScan(intent, callback)
        }
    }
}

