package com.adealink.frame.imkit.widget.cache

/**
 * 消息展示列表专用 list 当达到存储最大值后，底部插入新数据时，顶部数据丢弃， 顶部插入数据时，不考虑最大值，底部数据保留。
 *
 * @param <T> 范型
</T> */
class MessageList<T> : ArrayList<T> {
    /** 列表存储最大值  */
    private var mMaxCount: Int

    constructor(maxCount: Int, initialCapacity: Int) : super(initialCapacity) {
        mMaxCount = maxCount
    }

    constructor(maxCount: Int) {
        mMaxCount = maxCount
    }

    constructor(maxCount: Int, c: Collection<T>) : super(c) {
        mMaxCount = maxCount
    }

    override fun add(t: T): Boolean {
        val result = super.add(t)
        val overCount = size - mMaxCount
        // 超出最大值，先移除
        if (overCount > 0) {
            removeRange(0, overCount)
        }
        return result
    }

    override fun add(index: Int, element: T) {
        super.add(index, element)
        val overCount = size - mMaxCount
        // 超出最大值，先移除
        if (overCount > 0) {
            // 取中位值，大于中位移除首个索引，小于中位移除末尾索引
            if (index > mMaxCount / 2) {
                removeRange(0, overCount)
            }
        }
    }

    override fun addAll(c: Collection<T>): Boolean {
        val result = super.addAll(c)
        val overCount = size - mMaxCount
        // 超出最大值，先移除
        if (overCount > 0) {
            removeRange(0, overCount)
        }
        return result
    }

    override fun addAll(index: Int, c: Collection<T>): Boolean {
        val result = super.addAll(index, c)
        val overCount = size - mMaxCount
        // 超出最大值，先移除
        if (overCount > 0) {
            // 取中位值，大于中位移除首个索引，小于中位移除末尾索引
            if (index > mMaxCount / 2) {
                removeRange(0, overCount)
            }
        }
        return result
    }
}
