package com.all.pdfreader.pro.app.util

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import com.all.pdfreader.pro.app.R
import com.github.barteksc.pdfviewer.PDFView
import com.github.barteksc.pdfviewer.listener.OnDrawListener

class PDFHighlighter(
    private val pdfView: PDFView,
    private val searchManager: PDFSearchManager
) : OnDrawListener {

    enum class ClickType {
        NEXT,
        PREVIOUS
    }

    private var type = ClickType.NEXT

    private val highlightPaint = Paint().apply {
        color = 0x80FFD700.toInt() // 半透明黄色
        style = Paint.Style.FILL
    }

    private val highlightStrokePaint = Paint().apply {
        color = 0xFFFFA500.toInt() // 橙色边框
        style = Paint.Style.STROKE
        strokeWidth = 2f
    }

    private val selectedPaint = Paint().apply {
        color = 0x80FF4500.toInt() // 当前选中高亮，橙红色半透明
        style = Paint.Style.FILL
    }

    private val selectedStrokePaint = Paint().apply {
        color = 0xFFFF6347.toInt() // 当前选中边框，亮橙红
        style = Paint.Style.STROKE
        strokeWidth = 2f
    }

    private var currentPageHighlights: List<PDFSearchManager.TextPositionInfo> = emptyList()
    private var currentSelectedIndex: Int = -1

    /**
     * 设置当前页面的高亮
     */
    fun setCurrentPageHighlights(page: Int) {
        currentPageHighlights = searchManager.getHighlightsForPage(page)
        currentSelectedIndex = when (type) {
            ClickType.NEXT -> {
                if (currentPageHighlights.isNotEmpty()) 0 else -1
            }

            ClickType.PREVIOUS -> {
                if (currentPageHighlights.isNotEmpty()) currentPageHighlights.size - 1 else -1
            }
        }
        pdfView.invalidate()
    }

    /**
     * 清除当前高亮
     */
    fun clearCurrentHighlights() {
        currentPageHighlights = emptyList()
        currentSelectedIndex = -1
        pdfView.invalidate()
    }

    /**
     * 选中下一条高亮
     */
    fun selectNext(rid: ((Int) -> Unit)? = null) {
        type = ClickType.NEXT
        if (currentPageHighlights.isEmpty()) {//当前页没有对应的文字，直接跳转下一页
            val nextPage = searchManager.currentHighlightPage + 1
            pdfView.jumpTo(nextPage, true)
            return
        }
        if (currentSelectedIndex < currentPageHighlights.size - 1) {
            currentSelectedIndex++
            //下一页+，需要刷新
            pdfView.invalidate()
        } else {
            // 当前页最后一条，尝试跳到下一页
            val nextPage = searchManager.currentHighlightPage + 1
            if (nextPage < pdfView.pageCount) {
                pdfView.jumpTo(nextPage, true)
                currentSelectedIndex = 0
            } else {
                rid?.invoke(R.string.no_more_results)
            }
        }
    }

    /**
     * 选中上一条高亮
     */
    fun selectPrevious(rid: ((Int) -> Unit)? = null) {
        type = ClickType.PREVIOUS
        if (currentPageHighlights.isEmpty()) { // 当前页没有对应的文字，直接跳转上一页
            val prevPage = searchManager.currentHighlightPage - 1
            if (prevPage >= 0) {
                pdfView.jumpTo(prevPage, true)
            } else {
                rid?.invoke(R.string.no_more_results)
            }
            return
        } 
        if (currentSelectedIndex > 0) {
            currentSelectedIndex--
            pdfView.invalidate()
        } else {
            val prevPage = searchManager.currentHighlightPage - 1
            if (prevPage >= 0) {
                pdfView.jumpTo(prevPage, true)
                currentPageHighlights = emptyList()
                currentSelectedIndex = -1
            } else {
                rid?.invoke(R.string.no_more_results)
            }
        }
    }


    override fun onLayerDrawn(
        canvas: Canvas,
        pageWidth: Float,
        pageHeight: Float,
        displayedPage: Int
    ) {
        if (displayedPage != searchManager.currentHighlightPage) {
            searchManager.currentHighlightPage = displayedPage
//            setCurrentPageHighlights(displayedPage + 1)
        }

        currentPageHighlights.forEachIndexed { index, position ->
            try {
                val rect = position.getRelativeRect()
                val absoluteRect = RectF(
                    rect.left * pageWidth,
                    rect.top * pageHeight,
                    rect.right * pageWidth,
                    rect.bottom * pageHeight
                )

                val margin = 1f
                val paddedRect = RectF(
                    absoluteRect.left - margin,
                    absoluteRect.top - margin,
                    absoluteRect.right + margin,
                    absoluteRect.bottom + margin
                )

                if (index == currentSelectedIndex) {
                    canvas.drawRect(paddedRect, selectedPaint)
                    canvas.drawRect(paddedRect, selectedStrokePaint)
                } else {
                    canvas.drawRect(paddedRect, highlightPaint)
                    canvas.drawRect(paddedRect, highlightStrokePaint)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}
