package com.artifex.mupdf.viewer

import android.annotation.SuppressLint
import android.net.Uri
import android.util.DisplayMetrics
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.databinding.ActivityPdfTestBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfPagerAdapter
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfPresenter
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfView
import com.base.pdfviewerscannerwhite.utils.LogEx

/**
 * [com.artifex.mupdf.viewer.DocumentActivity]
 */
class PdfTestActivity : BaseActivity<ActivityPdfTestBinding>(), PdfView {

    private val TAG = "PdfTestActivity"

    private lateinit var pdfPresenter: PdfPresenter
    private lateinit var adapter: PdfPagerAdapter

    private var core: MuPDFCore? = null
    private lateinit var readerView: ReaderView
    private var searchTask: SearchTask? = null

    //居然是这样实现的
    private var mFlatOutline: ArrayList<OutlineActivity.Item>? = null

    private var mLayoutW = 440
    private var mLayoutH = 660
    private var mDisplayDPI = 0
    private val mLayoutEM = 10

    override val binding: ActivityPdfTestBinding by lazy {
        ActivityPdfTestBinding.inflate(layoutInflater)

    }
    private var uri: String = ""
    private var size = -1L
    private var path: String = ""


    override fun initView() {
        pdfPresenter = PdfPresenter(this, this)

        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        mDisplayDPI = metrics.densityDpi

        uri = intent.extras?.getString("uri") ?: ""
        path = intent.extras?.getString("path") ?: ""
        size = intent.extras?.getLong("size") ?: -1L

        initAdapter()

        core = openCore()
        initSearchTask()

        if (core?.needsPassword() == true) {

        } else {
            initReaderView()
            pdfPresenter.iniPdfPage(path)
        }


    }

    private fun initAdapter() {
        adapter = PdfPagerAdapter(path)
        adapter.clickAction = { pageIndex ->
        }
        binding.rvPager.adapter = adapter
    }


    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (binding.editSearch.isVisible) {
                noSearchUI()
            } else {
                finishToMain()
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.ivSearch.setOnClickListener {
            searchUi()
        }
        binding.editSearch.addTextChangedListener {
            if (SearchTaskResult.get() != null && it.toString() != SearchTaskResult.get().txt) {
                SearchTaskResult.set(null as SearchTaskResult?)
                readerView.resetupChildren()
            }
        }
        binding.editSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                search(1)
            }
            false
        }
    }

    private fun initSearchTask() {
        searchTask = object : SearchTask(this, core) {
            override fun onTextFound(result: SearchTaskResult) {
                SearchTaskResult.set(result)
                readerView.displayedViewIndex = result.pageNumber
                readerView.resetupChildren()
            }
        }
        SearchTaskResult.set(null)
    }

    private fun hideKeyboard() {
        val imm = this.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(binding.editSearch.windowToken, 0)
    }

    private fun search(direction: Int) {
        this.hideKeyboard()
        val displayPage: Int = readerView.displayedViewIndex
        val r = SearchTaskResult.get()
        val searchPage = r?.pageNumber ?: -1
        searchTask?.go(binding.editSearch.text.toString(), direction, displayPage, searchPage)
    }

    fun noSearchUI() {
        binding.editSearch.visibility = View.GONE

        binding.tvPdfName.visibility = View.VISIBLE
        binding.ivXuanzhuan.visibility = View.VISIBLE
        binding.ivMore.visibility = View.VISIBLE

    }

    private fun searchUi() {
        binding.tvPdfName.visibility = View.GONE
        binding.ivXuanzhuan.visibility = View.GONE
        binding.ivMore.visibility = View.GONE

        binding.editSearch.visibility = View.VISIBLE
        binding.editSearch.requestFocus()
    }


    /**
     * need size
     */
    private fun openCore(): MuPDFCore {
        return MuPDFCore(ContentInputStream(this.contentResolver, Uri.parse(uri), size), "application/pdf")
    }

    @SuppressLint("SetTextI18n")
    private fun initReaderView() {

        binding.tvPageCount.text = "1/${core?.countPages()}"

        readerView = object : ReaderView(this) {
            @SuppressLint("SetTextI18n")
            override fun onMoveToChild(i: Int) {
                LogEx.logDebug(TAG, "onMoveToChild $i")
                binding.tvPageCount.text = "${i + 1}/${core?.countPages()}"
                super.onMoveToChild(i)
            }

            override fun onTapMainDocArea() {
                super.onTapMainDocArea()
            }

            override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
                //文档内容能够根据不同的屏幕尺寸或布局自动重新排列的特性
                if (core?.isReflowable == true) {
                    mLayoutW = w * 72 / mDisplayDPI
                    mLayoutH = h * 72 / mDisplayDPI
                    relayoutDocument()
                } else {
                    refresh()
                }
            }


        }
        readerView.adapter = PageAdapter(this, core)


        binding.rl.addView(readerView)
    }

    fun relayoutDocument() {
        if (core != null) {
            val loc = core?.layout(readerView.mCurrent, mLayoutW, mLayoutH, mLayoutEM) ?: 0
            mFlatOutline = null
            readerView.mHistory?.clear()
            readerView.refresh()
            readerView.displayedViewIndex = loc
        }
    }

    override fun onPause() {
        super.onPause()
        searchTask?.stop()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun initPdfPageRv(items: List<PdfPageBean>) {
        adapter.submitList(items)
    }

}