package com.pdf.base.function

import com.compdfkit.core.document.CPDFDocument
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * @author: hubowen
 * @date: 2022/10/9
 * @description:
 */

/**
 * 页面旋转
 * CPDFDocument 页面翻转 array -> 页面的Num
 */
suspend fun CPDFDocument.pageRotate(array: IntArray, onPre: (() -> Unit)? = null, onSuccess: ((Boolean) -> Unit)? = null, onComplete: (() -> Unit)? = null) {
    var rotateSuccess = false
    withContext(Dispatchers.Main) {
        onPre?.invoke()
        withContext(Dispatchers.IO) {
            runCatching {
                array.map { index ->
                    pageAtIndex(index)?.apply {
                        rotateSuccess = setRotation(this.rotation + 90)
                        //如果有翻转失败就暂停
                        if (!rotateSuccess) return@map
                    }
                }
            }.onFailure {
                onSuccess?.invoke(false)
            }.onSuccess {
                onSuccess?.invoke(rotateSuccess)
            }
        }
        onComplete?.invoke()
    }
}

/**
 * 页面裁剪
 * CPDFDocument 页面裁剪 array -> 页面的Num
 */
suspend fun CPDFDocument.pageSplit(array: IntArray, onPre: (() -> Unit)? = null, onSuccess: ((Boolean) -> Unit)? = null, onComplete: (() -> Unit)? = null) {
    withContext(Dispatchers.Main) {
        onPre?.invoke()
        withContext(Dispatchers.IO) {
            runCatching {
                CPDFDocument.createDocument(context).apply {
                    importPages(this@pageSplit, array, 0).also {

                    }
                }
            }.onFailure {
                onSuccess?.invoke(false)
            }.onSuccess {
                onSuccess?.invoke(true)
            }
        }
        onComplete?.invoke()
    }
}

/**
 * 页面删除
 * CPDFDocument 页面删除 array -> 页面的Num
 */
suspend fun CPDFDocument.pageDelete(array: IntArray, onPre: (() -> Unit)? = null, onSuccess: ((Boolean) -> Unit)? = null, onComplete: (() -> Unit)? = null) {
    var deleteSuccess = false
    withContext(Dispatchers.Main) {
        onPre?.invoke()
        withContext(Dispatchers.IO) {
            runCatching {
                deleteSuccess = removePages(array)
            }.onFailure {
                onSuccess?.invoke(false)
            }.onSuccess {
                onSuccess?.invoke(deleteSuccess)
            }
        }
        onComplete?.invoke()
    }
}