package com.pan_american.android.util

import android.text.InputFilter
import android.text.Spanned

class MoneyInputFilter : InputFilter {

    companion object {
        //保留小数点位数
        const val POINT_LENGTH = 2
    }

    override fun filter(
        //将要输入的字符串,如果是删除操作则为空
        source: CharSequence,
        //将要输入的字符串起始下标，一般为0
        inputStart: Int,
        //start + source字符的长度
        inputLength: Int,
        //输入之前文本框中的内容
        dest: Spanned,
        //将会被替换的起始位置
        replaceStart: Int,
        //replaceStart+将会被替换的字符串长度
        replaceLength: Int
    ): CharSequence {
        val start = dest.subSequence(0, replaceStart)
        val end = dest.subSequence(replaceLength, dest.length)
        //字符串变化后的结果
        val target = start.toString() + source + end
        //将要被替换的字符串
        val backup = dest.subSequence(replaceStart, replaceLength)

        //不允许第一个字符为.
        if (target.indexOf(".") == 0) {
            return backup
        }

        //不允许出现0123、0456这类字符串
        if (target.startsWith("0") && !target.startsWith("0.") && "0" != target) {
            return backup
        }

        //限制小数点后面只能有两位小数
        val index = target.indexOf(".")
        if (index >= 0 && index + POINT_LENGTH + 2 <= target.length) {
            return backup
        }

        return source
    }
}