package com.base.pdfreaderallpdfreader.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 androidx.lifecycle.ViewModel
import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions
import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResult
import java.io.File

class MainViewModel : ViewModel() {

    private var scannerLauncher: ActivityResultLauncher<IntentSenderRequest>? = null

    var handleActivityGmsScanResult: ((imageUri: Uri?, pdfUri: Uri?) -> Unit)? = null

    private var scannerLauncherRegister: Boolean = false
    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
                    handleActivityGmsScanResult?.invoke(imageUri, pdfUri)
                } else {
                    handleActivityGmsScanResult?.invoke(null, null)
                }
            }

        scannerLauncherRegister = true
    }

    fun starGmsScan(activity: Activity) {
        runCatching {
            if (scannerLauncher == null && !scannerLauncherRegister) return
            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 ->
                }
        }
    }

    fun copyFile(file: File, newFile: File) {
        runCatching {
            file.copyTo(newFile, true)
        }
    }

}