package com.kdanmobile.reader.screen.adapter

import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.model.SearchResultInfo
import java.util.ArrayList

class SearchAdapter(private var width: Int): BaseAdapter() {
    private var list: MutableList<SearchResultInfo> = ArrayList()
    private var selected = -1

    fun clear() {
        list.clear()
    }

    fun add(list: List<SearchResultInfo>) {
        this.list.addAll(list)
    }

    override fun getCount(): Int {
        return list.size
    }

    override fun getItem(position: Int): Any {
        return list[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    fun setSelected(position: Int) {
        this.selected = position
        notifyDataSetChanged()
    }

    override fun getView(position: Int, view: View?, parent: ViewGroup): View {
        var view1 = view
        val item = list[position]
        val holderView: HolderView
        if (view1 == null) {
            view1 = LayoutInflater.from(parent.context).inflate(R.layout.item_search, null) as View
            holderView = HolderView()
            holderView.tv_result = view1.findViewById<View>(R.id.tv_fragmentPdfReaderSearchLvItem_result) as TextView
            holderView.tv_page = view1.findViewById<View>(R.id.tv_fragmentPdfReaderSearchLvItem_page) as TextView
            holderView.view = view1.findViewById(R.id.view_fragmentPdfReaderSearchLvItem_selected)
            holderView.rl = view1 .findViewById<View>(R.id.rl_fragmentPdfReaderSearchLvItem_) as RelativeLayout
            val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            params.leftMargin = 21 * width / 800
            params.rightMargin = 21 * width / 800
            params.topMargin = 8 * width / 800
            holderView.rl.layoutParams = params
            view1.tag = holderView
        } else {
            holderView = view1.tag as HolderView
        }

        if (selected == position) {
            holderView.view.setBackgroundResource(R.drawable.rectangle_6633b5e5)
        } else {
            holderView.view.setBackgroundResource(R.drawable.rectangle_0000)
        }

        holderView.tv_result.text = Html.fromHtml(item.result)
        holderView.tv_page.text = (item.page + 1).toString()

        return view1
    }

    private inner class HolderView {
        lateinit var rl: RelativeLayout
        lateinit var tv_result: TextView
        lateinit var tv_page: TextView
        lateinit var view: View
    }
}
