package com.base.pdfreaderallpdfreader.ui.pdf

import android.content.Intent
import androidx.activity.addCallback
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.bean.ConstObject.DO_MERGE_PDF
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.databinding.ActivityPdfMergeBinding
import com.base.pdfreaderallpdfreader.ui.view.NameDialog.showDocumentRenameDialog
import com.base.pdfreaderallpdfreader.ui.view.PwdDialog.showPdfPwdDialog
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatTime2
import com.base.pdfreaderallpdfreader.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 pdfViewModel: PdfViewModel
    private lateinit var adapter: PdfMergeAdapter

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

    override fun initView() {
        pdfViewModel = ViewModelProvider(this)[PdfViewModel::class.java]
        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", pdfViewModel.createNewPdfPath(this@PdfMergeActivity, 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()
    }
}