package com.pdf.base.function

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LifecycleCoroutineScope
import com.compdfkit.core.document.CPDFDocument
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @author: hubowen
 * @date: 2022/9/20
 * @description: LogicFunction 负责PDF的 打开逻辑，保存逻辑
 */

/**
 * 验证文档
 * onSuccess 返回一个正常的Document
 * onError 错误返回
 */
fun LifecycleCoroutineScope.onVerifyDocument(context: Context, uri: Uri?, absolutePath: String?, password: String? = "", onSuccess: ((CPDFDocument) -> Unit)?, onError: (() -> Unit)? = null) {
    launch(Dispatchers.IO) {
        context.toCPDFDocument(uri, absolutePath, password, {
            onSuccess?.invoke(it)
        }, {
            onError?.invoke()
        })
    }
}

/**
 * 转换至 Document对象，这里单独写出来，提供单独的document，用来做功能
 * onSuccess 返回一个正常的Document
 * NeedExit 错误返回
 */
suspend fun Context.toCPDFDocument(uri: Uri?, absolutePath: String?, password: String? = "", onSuccess: ((CPDFDocument) -> Unit)?, onError: (() -> Unit)? = null) {
    var document: CPDFDocument? = null

    fun getCPDFDocument(password: String? = null): CPDFDocument.PDFDocumentError? {
        return try {
            when (absolutePath.isNullOrEmpty()) {
                true -> {
                    uri?.let { uri_ ->
                        CPDFDocument(this).let {
                            document = it
                            when {
                                password.isNullOrEmpty() -> it.open(uri_)
                                else -> it.open(uri_, password)
                            }
                        }
                    }
                }
                else -> {
                    CPDFDocument(this).let {
                        document = it
                        when {
                            password.isNullOrEmpty() -> it.open(absolutePath)
                            else -> it.open(absolutePath, password)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            onError?.invoke()
            null
        }
    }

    runCatching {
        getCPDFDocument(password)?.apply {
            withContext(Dispatchers.Main) {
                when (this@apply) {
                    CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess -> {
                        document?.run { onSuccess?.invoke(this) }
                    }
                    CPDFDocument.PDFDocumentError.PDFDocumentErrorPassword -> {
                        Log.e("AAAA", "PDFDocumentErrorPassword")
//                        (ActivitysUtils.current() as AppCompatActivity?)?.apply {
//                            PdfPasswordEnterDialog(tPdfDocument, uri, absolutePath).onShow(supportFragmentManager) {
//                                when {
//                                    it -> onFinish?.invoke(tPdfDocument)
//                                    else -> needExit?.invoke()
//                                }
//                            }
//                        }
                    }
                    else -> {
                        Log.e("AAAA", this@apply.toString())
//                        (ActivitysUtils.current() as AppCompatActivity?)?.let {
//                            BaseDialogFragmentHelper.showConfirmTips(
//                                it.supportFragmentManager,
//                                title = getString(R.string.pdf_damaged_title),
//                                message = getString(R.string.pdf_damaged_content),
//                                isCancelable = false,
//                                isCanceledOnTouchOutside = false
//                            ) {
//                                needExit?.invoke()
//                            }
//                        }
                    }
                }
            }
        }
    }.onFailure {
        onError?.invoke()
    }
}

/**
 * 保存Document 这里有一个逻辑，先增量保存如果失败则进行全量保存。
 */
suspend fun CPDFDocument.onSaveDocument(isNeedClose: Boolean = false, onPre: (() -> Unit)? = null, onSuccess: ((Boolean) -> Unit)? = null, onComplete: (() -> Unit)? = null) {
    var isSaveSuccess: Boolean
    withContext(Dispatchers.Main) {
        onPre?.invoke()
        withContext(Dispatchers.IO) {
            runCatching {
                if (hasChanges()) {
                    //增量保存
                    isSaveSuccess = save()
                    //全量保存
                    if (!isSaveSuccess) isSaveSuccess = save(CPDFDocument.PDFDocumentSaveType.PDFDocumentSaveNoIncremental)
                }
            }.onFailure {
                Log.e("pdf_base", "save_failed")
                onSuccess?.invoke(false)
            }.onSuccess {
                Log.e("pdf_base", "save_success")
                onSuccess?.invoke(true)
            }
        }
        //关闭文档
        if (isNeedClose) close()
        onComplete?.invoke()
    }

}

/**
 * 另存PDF文件
 */

/**
 * 保存Flattened副本
 */