function findQrCodeScannerComponents(data, result = []) {
  if (!Array.isArray(data)) data = [data];
  for (const item of data) {
    if ("components" in item) {
      findQrCodeScannerComponents(item.components, result);
    }
    if ("children" in item) {
      findQrCodeScannerComponents(item.children, result);
    }
    if (item.name === "QrCodeScanner") {
      result.push(item);
    }
  }

  return result;
}

export const buildQrCodeScannerImports = (fragment) => {
  if (findQrCodeScannerComponents(fragment).length == 0) return "";

  return `
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.view.SurfaceHolder
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.google.android.gms.vision.CameraSource
import com.google.android.gms.vision.Detector
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
import com.manaknight.app.extensions.viewBinding
import java.io.IOException
     `;
};

export const getQrCodeScannerFields = (fragment) => {
  if (findQrCodeScannerComponents(fragment).length == 0) return "";

  return `
    private val requestCodeCameraPermission = 1001
    private lateinit var cameraSource: CameraSource
    private lateinit var barcodeDetector: BarcodeDetector
    private var scannedValue = ""


    private val cameraPermissionResultReceiver = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
        if (it) {
            // permission granted
            setupControls()
        } else {
            // permission denied
            Toast.makeText(activity, "Permission Denied", Toast.LENGTH_SHORT).show()
        }
    }
    `;
};

export const generateQrCodeScannerFragmentBinding = (fragment) => {
  if (findQrCodeScannerComponents(fragment).length == 0) return "";

  return `
        val view = binding.root

        if (activity?.checkSelfPermission(android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
        ) {
            cameraPermissionResultReceiver.launch(Manifest.permission.CAMERA)
        } else {
            setupControls()
        }

        val aniSlide: Animation =
            AnimationUtils.loadAnimation(activity, R.anim.scanner_animation)
        binding.barcodeLine.startAnimation(aniSlide)
    `;
};

export const generateQrCodeScannerFunction = (fragment, configuration) => {
  if (findQrCodeScannerComponents(fragment).length == 0) return "";

  return `
    private fun setupControls() {
        barcodeDetector =
            BarcodeDetector.Builder(activity).setBarcodeFormats(Barcode.ALL_FORMATS).build()

        cameraSource = CameraSource.Builder(activity, barcodeDetector)
            .setRequestedPreviewSize(1920, 1080)
            .setAutoFocusEnabled(true) //you should add this feature
            .build()

        binding.cameraSurfaceView.getHolder().addCallback(object : SurfaceHolder.Callback {
            @SuppressLint("MissingPermission")
            override fun surfaceCreated(holder: SurfaceHolder) {
                try {
                    //Start preview after 1s delay
                    cameraSource.start(holder)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            @SuppressLint("MissingPermission")
            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
                try {
                    cameraSource.start(holder)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                cameraSource.stop()
            }
        })


        barcodeDetector.setProcessor(object : Detector.Processor<Barcode> {
            override fun release() {
                Toast.makeText(activity, "Scanner has been closed", Toast.LENGTH_SHORT)
                    .show()
            }

            override fun receiveDetections(detections: Detector.Detections<Barcode>) {
                val barcodes = detections.detectedItems
                if (barcodes.size() == 1) {
                    scannedValue = barcodes.valueAt(0).rawValue

                    activity?.runOnUiThread {
                        cameraSource.stop()
                        Toast.makeText(activity, "value- $scannedValue", Toast.LENGTH_SHORT).show()
                    }
                }else
                {
                    Toast.makeText(activity, "value- else", Toast.LENGTH_SHORT).show()

                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraSource.stop()
    }
    `;
};
