package cn.muchinfo.rma.view.autoWidget

fun <T> List<T>.opt(index: Int): T? {
    if (size <= index || index < 0) {
        return null
    }
    return get(index)
}

fun <T> List<T>.toArrayList(): ArrayList<T> {
    return (this as? ArrayList) ?: ArrayList<T>().apply {

        addAll(this@toArrayList)
    }
}

fun <T> List<T>.replace(entity: T, block: ((T) -> Boolean)): List<T> {
    val mutableList = (this as? ArrayList) ?: arrayListOf<T>().apply { addAll(this@replace) }
    indexOfFirst { block.invoke(it) }.takeIf { it >= 0 }?.let {
        mutableList.removeAt(it)
        mutableList.add(it, entity)
    }
    return mutableList
}

fun <T> List<T>.remove(block: (T) -> Boolean): List<T> {
    val mutableList = (this as? ArrayList) ?: arrayListOf<T>().apply { addAll(this@remove) }
    indexOfFirst { block.invoke(it) }.takeIf { it >= 0 }?.let {
        mutableList.removeAt(it)
    }
    return mutableList
}

fun <T> List<T>.replaceOrInsert(entity: T, index: Int = 0, block: ((T) -> Boolean)): List<T> {
    val mutableList = (this as? ArrayList)
            ?: arrayListOf<T>().apply { addAll(this@replaceOrInsert) }
    val existEntityIndex = indexOfFirst { block.invoke(it) }.takeIf { it >= 0 }
    if (existEntityIndex != null) {
        mutableList.removeAt(existEntityIndex)
        mutableList.add(existEntityIndex, entity)
    } else if (index in 1..(size - 1)) {
        mutableList.add(index, entity)
    }
    return mutableList
}