package com.all.pdfreader.pdf.reader.ui.act

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.all.pdfreader.pdf.reader.PRApp
import com.all.pdfreader.pdf.reader.R
import com.all.pdfreader.pdf.reader.databinding.ActPictureSelectorBinding
import com.all.pdfreader.pdf.reader.model.PdfPickerSource
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.all.pdfreader.pdf.reader.util.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnMediaEditInterceptListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.style.SelectMainStyle
import com.luck.picture.lib.utils.DateUtils
import com.yalantis.ucrop.UCrop
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

class PictureSelectorActivity : BaseActivity() {
    private lateinit var binding: ActPictureSelectorBinding
    override val rootBottomView: View?
        get() = binding.rootBottomLayout
    override val TAG = "PictureSelectorActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActPictureSelectorBinding.inflate(layoutInflater)
        setContentView(binding.root)
        AnalyticsUtils.logEvent(AnalyticsUtils.Event.TUTO_PDF_SHOW)
        setupImmersionBar {
            statusBarView(binding.view)
            statusBarDarkFont(false)
        }
        openImagePicker()
    }

    private fun openImagePicker() {
        val selectorStyle = PictureSelectorStyle().apply {
            selectMainStyle = SelectMainStyle().apply {
                isSelectNumberStyle = true
                isPreviewSelectNumberStyle = true
                selectBackground = R.drawable.num_checkbox_selector
            }
        }
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(selectorStyle)
            .setImageEngine(GlideEngine.createGlideEngine())
            .setImageSpanCount(3)
            .isGif(false)
            .isFastSlidingSelect(true)
            .setSelectionMode(SelectModeConfig.MULTIPLE)
            .setMaxSelectNum(50)
            .isPreviewFullScreenMode(false)
            .setCompressEngine(object : CompressFileEngine {
                override fun onStartCompress(
                    context: Context?,
                    source: ArrayList<Uri?>?,
                    call: OnKeyValueResultCallbackListener?
                ) {
                    Luban.with(context)
                        .load(source)
                        .ignoreBy(100)
                        .setCompressListener(object : OnNewCompressListener {
                            override fun onStart() {

                            }

                            override fun onSuccess(
                                source: String?,
                                compressFile: File?
                            ) {
                                call?.onCallback(source, compressFile?.absolutePath)
                            }

                            override fun onError(source: String?, e: Throwable?) {
                                call?.onCallback(source, null)
                            }
                        })
                        .launch()
                }
            })
            .setEditMediaInterceptListener(object : OnMediaEditInterceptListener {
                override fun onStartMediaEdit(
                    fragment: Fragment, currentLocalMedia: LocalMedia, requestCode: Int
                ) {
                    val currentEditPath = currentLocalMedia.getAvailablePath()
                    val inputUri = if (PictureMimeType.isContent(currentEditPath)) {
                        currentEditPath.toUri()
                    } else {
                        Uri.fromFile(File(currentEditPath))
                    }
                    val destinationUri = Uri.fromFile(
                        File(
                            getSandboxPath(), DateUtils.getCreateFileName("CROP_") + ".jpeg"
                        )
                    )
                    val uCrop = UCrop.of<Any>(inputUri, destinationUri)
                    val buildOptions = UCrop.Options().apply {
                        isDarkStatusBarBlack(true)
                    }
                    uCrop.withOptions(buildOptions)
                    uCrop.start(this@PictureSelectorActivity, fragment, requestCode)
                }

            }).buildLaunch(R.id.fragment_container,object : OnResultCallbackListener<LocalMedia>{
                override fun onResult(result: ArrayList<LocalMedia>) {
                    logDebug("forResult ->${result.size}")
                    if (result.isNotEmpty()) {
                        // result 中可能有带裁剪的 Uri 或原图 Uri
                        // 取出路径列表
                        val paths = result.mapNotNull { media ->
                            media.availablePath
                        }
                        if (paths.isEmpty()) {
                            return
                        }
                        val intent = PdfResultActivity.createIntentInputFile(
                            this@PictureSelectorActivity,
                            ArrayList(paths),
                            PdfPickerSource.IMAGES_TO_PDF
                        )
                        startActivity(intent)
                        finish()
                    }
                }

                override fun onCancel() {
                    finish()
                }

            })

//            .forResult(object : OnResultCallbackListener<LocalMedia> {
//                override fun onResult(result: ArrayList<LocalMedia>) {
//                    logDebug("forResult ->${result.size}")
//                    if (result.isNotEmpty()) {
//                        // result 中可能有带裁剪的 Uri 或原图 Uri
//                        // 取出路径列表
//                        val paths = result.mapNotNull { media ->
//                            media.availablePath
//                        }
//                        if (paths.isEmpty()) {
//                            return
//                        }
//                        val intent = PdfResultActivity.createIntentInputFile(
//                            this@PictureSelectorActivity,
//                            ArrayList(paths),
//                            PdfPickerSource.IMAGES_TO_PDF
//                        )
//                        startActivity(intent)
//                    }
//                }
//
//                override fun onCancel() {
//                    logDebug("onCancel")
//                }
//            })

//        supportFragmentManager.beginTransaction()
//            .add(R.id.fragment_fl, selectorFragment, selectorFragment.getFragmentTag())
//            .addToBackStack(selectorFragment.getFragmentTag())
//            .commitAllowingStateLoss();
    }

    fun getSandboxPath(): String {
        val dir = File(PRApp.getContext().externalCacheDir, "SandboxPdfPro")
        if (!dir.exists()) dir.mkdirs()
        return dir.absolutePath
    }
}