package com.adealink.frame.imkit.widget.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import java.util.Collections

abstract class BaseListViewAdapter<T> : BaseAdapter {
    private var context: Context? = null
    protected var list: MutableList<T>

    constructor() {
        list = ArrayList()
    }

    constructor(context: Context?) {
        this.context = context
        list = ArrayList()
    }

    protected fun <T : View> findViewById(view: View, id: Int): T {
        return view.findViewById<View>(id) as T
    }

    fun findPosition(message: T): Int {
        var index = count
        var position = -1
        while (index-- > 0) {
            if (message == getItem(index)) {
                position = index
                break
            }
        }
        return position
    }

    fun findPosition(id: Long): Int {
        var index = count
        var position = -1
        while (index-- > 0) {
            if (getItemId(index) == id) {
                position = index
                break
            }
        }
        return position
    }

    fun addCollection(collection: Collection<T>) {
        list.addAll(collection)
    }

    @SafeVarargs
    fun addCollection(vararg collection: T) {
        Collections.addAll(list, *collection)
    }

    fun add(t: T) {
        list.add(t)
    }

    fun add(t: T, position: Int) {
        list.add(position, t)
    }

    fun remove(position: Int) {
        list.removeAt(position)
    }

    fun removeAll() {
        list.clear()
    }

    fun clear() {
        list.clear()
    }

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

    override fun getItem(position: Int): T? {
        if (position >= list.size) return null

        return list[position]
    }

    override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
        bindView(convertView, position, getItem(position))
        return convertView
    }

    protected abstract fun newView(context: Context?, position: Int, group: ViewGroup?): View

    protected abstract fun bindView(v: View?, position: Int, data: T?)
}
