package com.yidian.bcommon.widget

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * 手机号输入的TextWatcher
 */
class PhoneNumberTextWatcher(private var editText: EditText, private var inputCallback: EditTextInputCallback) : TextWatcher {
  private var isDelete = false
  private var lastContentLength = 0
  private val sb = StringBuffer()

  override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

  }

  override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    sb.delete(0, sb.length)
    sb.append(s)
    isDelete = s?.length!! <= lastContentLength
    if (!isDelete && (s.length == 4 || s.length == 9)) {
      if (s.length == 4) {
        sb.insert(3, " ")
      } else {
        sb.insert(8, " ")
      }
      setContent(sb)
    }
    if (isDelete && (s.length == 4 || s.length == 9)) {
      sb.deleteCharAt(sb.length - 1)
      setContent(sb)
    }
    lastContentLength = sb.length
    inputCallback.inputCallback(sb.toString())
  }

  override fun afterTextChanged(s: Editable?) {

  }

  private fun setContent(sb: StringBuffer) {
    editText.setText(sb.toString())
    editText.setSelection(sb.length)
  }
}
