package com.imyeyu.fx.ui.components;

import com.imyeyu.java.TimiJava;
import com.imyeyu.utils.Calc;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 * 数字输入框
 *
 * @author 夜雨
 * @since 2021-12-29 21:59
 */
public class NumberField extends TextField {

	/** 数值 */
	private final DoubleProperty value;

	private boolean isBackSpace = false;

	/** 默认构造 */
	public NumberField() {
		this("");
	}

	/**
	 * 数字输入组件构造
	 *
	 * @param text 默认数值字符串
	 */
	public NumberField(String text) {
		super(text);

		value = new SimpleDoubleProperty();
		value.addListener((obs, o, newValue) -> {
			if (newValue.doubleValue() % 1 == 0) {
				setText(String.valueOf(newValue.intValue()));
			} else {
				setText(String.valueOf(newValue.doubleValue()));
			}
		});

		textProperty().addListener((obs, o, newText) -> {
			if (Calc.isNumber(newText)) {
				if (getDouble() % 1 == 0) {
					value.set(getInt());
				} else {
					value.set(getDouble());
				}
			}
		});
		addEventFilter(KeyEvent.KEY_PRESSED, e -> isBackSpace = e.getCode() == KeyCode.BACK_SPACE);
		setTextFormatter(new TextFormatter<>(c -> {
			String newText = c.getControlNewText();
			if (TimiJava.isNotEmpty(newText)) {
				if (newText.equals("+") || newText.equals("-")) {
					return c;
				}
				if (Calc.isNumber(newText)) {
					if (isBackSpace && newText.endsWith(".")) {
						c.setRange(c.getRangeStart() - 1, c.getRangeEnd());
						return c;
					}
					return c;
				} else {
					return null;
				}
			} else {
				return c;
			}
		}));
	}

	/**
	 * 设置当前值
	 *
	 * @param number 当前值
	 */
	public void setValue(Number number) {
		setText(String.valueOf(number));
	}

	/**
	 * 获取为双精度浮点值
	 *
	 * @return 双精度浮点值
	 */
	public double getDouble() {
		return getValue().doubleValue();
	}

	/**
	 * 获取为长整值
	 *
	 * @return 长整值
	 */
	public long getLong() {
		return getValue().longValue();
	}

	/**
	 * 获取为短整值
	 *
	 * @return 短整值
	 */
	public int getInt() {
		return getValue().intValue();
	}

	/**
	 * 获取为单精度浮点值
	 *
	 * @return 单精度浮点值
	 */
	public float getFloat() {
		return getValue().floatValue();
	}

	/**
	 * 获取数字对象
	 *
	 * @return 数字对象
	 */
	public Number getValue() {
		if (TimiJava.isEmpty(getText())) {
			return null;
		}
		return Double.parseDouble(getText());
	}

	/**
	 * 获取数值属性
	 *
	 * @return 数值属性
	 */
	public DoubleProperty valueProperty() {
		return value;
	}

	/**
	 * 设置值
	 *
	 * @param value 值
	 */
	public void setValue(double value) {
		this.value.set(value);
	}
}
