package com.base.pdfviewerscannerwhite.ui.main

import android.app.Activity
import android.content.IntentSender
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.base.pdfviewerscannerwhite.utils.ToastUtils.toast
import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions
import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResult

class MainPresenter(
    val mainView: MainView
) {

    private lateinit var scannerLauncher: ActivityResultLauncher<IntentSenderRequest>

    fun initScannerLauncher(appCompatActivity: AppCompatActivity) {
        scannerLauncher =
            appCompatActivity.registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { activityResult ->

                val resultCode = activityResult.resultCode
                val result = GmsDocumentScanningResult.fromActivityResultIntent(activityResult.data)
                appCompatActivity.toast("回调1")
                if (resultCode == Activity.RESULT_OK && result != null) {
                    val pages = result.pages
                    appCompatActivity.toast("回调2 ${pages?.size}")
                    var imageUri = Uri.EMPTY
                    if (!pages.isNullOrEmpty()) {
                        appCompatActivity.toast("回调3")
                        imageUri = pages[0].imageUri
                    }
                    val pdfUri = result.pdf?.uri ?: Uri.EMPTY
                    mainView.handleActivityGmsScanResult(imageUri, pdfUri)
                }
            }
    }

    fun starGmsScan(activity: Activity) {
        val options =
            GmsDocumentScannerOptions.Builder()
                .setScannerMode(GmsDocumentScannerOptions.SCANNER_MODE_BASE)
                .setResultFormats(GmsDocumentScannerOptions.RESULT_FORMAT_PDF)
                .setGalleryImportAllowed(true)

        options.setScannerMode(GmsDocumentScannerOptions.SCANNER_MODE_FULL)

        val pageLimit = 1
        options.setPageLimit(pageLimit)


        GmsDocumentScanning.getClient(options.build())
            .getStartScanIntent(activity)
            .addOnSuccessListener { intentSender: IntentSender ->
                scannerLauncher.launch(IntentSenderRequest.Builder(intentSender).build())
            }
            .addOnFailureListener { e: Exception ->
            }

    }
}