package com.okolabo.kotlinfx

import javafx.beans.property.ObjectProperty
import java.util.regex.Pattern
import kotlin.properties.Delegates
import javafx.beans.property.SimpleObjectProperty

public open class PatternTextField : javafx.scene.control.TextField() {

    class object {
        val NUMBER_ONLY by Delegates.lazy { Pattern.compile("[0-9]") }
        val ALPHABET_ONLY by Delegates.lazy { Pattern.compile("[a-z]", Pattern.CASE_INSENSITIVE) }
    }

    private val verifier : ObjectProperty<Pattern> = SimpleObjectProperty(this, "Verifier")

    public fun setVerifier(pattern: Pattern): Unit = verifier.set(pattern)
    public fun getVerifier(): Pattern = verifier.get()!!

    public override fun replaceText(start: Int, end: Int, text: String?) {
        if (text != null) {
            if (text.equals("") || getVerifier().matcher(text).find()) {
                super.replaceText(start, end, text);
            }
        }
    }

    public override fun replaceSelection(text: String?) {
        if (text != null) {
            if (text.equals("") || getVerifier().matcher(text!!).find()) {
                super.replaceSelection(text)
            }
        }
    }
}