package com.base.pdfviewerscannerwhite.ui.document.pdf

import android.content.Intent
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_MERGE_PDF
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfMergeBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.MyApplication
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDocumentRenameDialog
import com.base.pdfviewerscannerwhite.ui.view.PdfDialog.showPdfPwdDialog
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime2
import com.base.pdfviewerscannerwhite.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue


class PdfMergeActivity : BaseActivity<ActivityPdfMergeBinding>() {

    private val TAG = "PdfMergeActivity"
    override val binding: ActivityPdfMergeBinding by lazy {
        ActivityPdfMergeBinding.inflate(layoutInflater)
    }
    private lateinit var pdfPresenter: PdfPresenter
    private lateinit var adapter: PdfMergeAdapter

    override fun onResume() {
        super.onResume()
        updateAppLanguage(MyApplication.pdfMergeLanguage) {
            MyApplication.pdfMergeLanguage = it
        }
    }

    override fun initView() {
        pdfPresenter = PdfPresenter(this)
        initAdapter()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvAdd.setOnClickListener {
            finish()
        }
        binding.tvBtnNext.setOnClickListener {
            verificationPasswordDialogs {

                showDocumentRenameDialog(name = "Merge_${System.currentTimeMillis().toFormatTime2()}", okAction = { name ->
                    startActivity(Intent(this, PdfLoadingActivity::class.java).apply {
                        putExtra("doWhat", DO_MERGE_PDF)
                        putExtra("newPath", pdfPresenter.createNewPdfPath(name))
                    })
                })

            }
        }
    }

    private fun verificationPasswordDialogs(callBack: () -> Unit) {
        val queue: BlockingQueue<DocumentBean> = ArrayBlockingQueue(1)

        val pwdItemList = mergePdfList.filter { it.state == 1 }.toMutableList()

        if (pwdItemList.isNotEmpty()) {
            LogEx.logDebug(TAG, "verificationPasswordDialogs1")
            val verifiedList = arrayListOf<DocumentBean>()
            val first = pwdItemList[0]
            queue.put(first)
            pwdItemList.removeAt(0)
            LogEx.logDebug(TAG, "verificationPasswordDialogs2")
            lifecycleScope.launch(Dispatchers.IO) {
                while (isActive) {
                    val item: DocumentBean = queue.take()
                    LogEx.logDebug(TAG, "pwdItem =${item.path}")
                    if (item.path == "Cancel") {
                        break
                    }
                    launch(Dispatchers.Main) {
                        showPdfPwdDialog(item.state, item.path, isCheckPwd = true, verificationAction = { pwd ->
                            item.password = pwd
                            verifiedList.add(item)
                            if (pwdItemList.isNotEmpty()) {
                                val next = pwdItemList[0]
                                queue.put(next)
                                pwdItemList.removeAt(0)
                            } else {
                                queue.put(DocumentBean(path = "Cancel"))
                            }
                        }, cancelAction = {
                            cancel()
                        })
                    }

                }
                LogEx.logDebug(TAG, "verificationPasswordDialogs3 ${verifiedList.size}")
                verifiedList.forEach { verifiedItem ->
                    mergePdfList.find { it.path == verifiedItem.path }?.password = verifiedItem.password
                }
                mergePdfList.forEach {
                    LogEx.logDebug(TAG, "密码=" + it.password)
                }
                launch(Dispatchers.Main) {
                    callBack.invoke()
                }
            }

        } else {
            callBack.invoke()
        }
    }

    private fun initAdapter() {
        val callBack = PdfMergeItemTouchHelperCallBack()
        val itemTouchHelper = ItemTouchHelper(callBack)
        itemTouchHelper.attachToRecyclerView(binding.rv)
        adapter = PdfMergeAdapter(itemTouchHelper, callBack)
        adapter.removeAction = {
            mergePdfList.remove(it)
            binding.tvBtnNext.isEnabled = mergePdfList.size >= 2
        }
        binding.rv.adapter = adapter

        callBack.changeListOrder = { olderPosition, newPosition ->
            val bean = mergePdfList[olderPosition]
            mergePdfList.remove(bean)
            mergePdfList.add(newPosition, bean)

            mergePdfList.forEach {
                LogEx.logDebug(TAG, "mergePdfList ${it.path}")
            }

            adapter.items.forEach {
                LogEx.logDebug(TAG, "items ${it.path}")
            }

//            adapter.items = mergePdfList
        }

        mergePdfList.let { adapter.submitList(it) }
        binding.tvBtnNext.isEnabled = mergePdfList.size >= 2
    }

    companion object {
        val mergePdfList: ArrayList<DocumentBean> = arrayListOf()
    }
}