package danielcortes.xyz.views.components;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.NumberFormat;
import javax.swing.JTextField;
import org.mariuszgromada.math.mxparser.Expression;

public class DoubleFormatedTextField extends JTextField {

  private double value;
  private NumberFormat nf;

  public DoubleFormatedTextField() {
    super();

    this.nf = NumberFormat.getIntegerInstance();
    this.nf.setMaximumFractionDigits(2);

    this.addFocusListener(new FocusListener() {
      @Override
      public void focusGained(FocusEvent e) {
        DoubleFormatedTextField.this.select(0, getText().length());
      }

      @Override
      public void focusLost(FocusEvent e) {
        DoubleFormatedTextField.this.readValue();
        DoubleFormatedTextField.this.formatText();
      }
    });
  }

  public double getValue() {
    this.readValue();
    return this.value;
  }

  public void setValue(double value) {
    this.value = value;
    this.formatText();
  }

  private void readValue() {
    String currentText = this.getText();
    String stripedDots = currentText.replace(".", "");
    String replacedPeriods = stripedDots.replace(",", ".");
    Expression expression = new Expression(replacedPeriods);

    if (expression.checkSyntax()) {
      this.value = expression.calculate();
    } else {
      this.value = 0;
    }

  }

  private void formatText() {
    this.setText(nf.format(this.value));
  }
}
