package leigh.elements.jfoenix.type1;

import com.jfoenix.controls.JFXTextArea;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import leigh.elements.ElementBase;
import leigh.elements.javafx.type1.ElementJFX;
import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.type1.TextAreaElement;
import leigh.eo.EO;
import leigh.eo.EOListener;
import leigh.eo.EditEventGenerator;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.Snavig;

import java.io.Serializable;

public class TextAreaJFoenix extends ElementBase implements ElementJFX, EOListener {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(DateFieldElementJFoenix.class);
    private HBox hbox = new HBox();
    private JFXTextArea textArea = new JFXTextArea();
    private VBox vbox = new VBox();

    // Whether we should ignore the next change event. We do this to avoid a loop.

    protected TextAreaJFoenix(EO cfg, AppScreenInstance screen) {
        super(cfg);

        textArea.getStyleClass().add("vds-field-textarea");

        Label label = new Label(cfg.getValueString(TextAreaElement.KEY_LABEL));

        String tooltip = cfg.getValueString(TextAreaElement.KEY_TOOLTIP);
        if (tooltip != null) {
            Tooltip tt = new Tooltip();
            tt.setText(tooltip);
            textArea.setTooltip(tt);
        }

        ((EditEventGenerator) cfg.getEditTracker()).addListener(cfg, this);

        String value = cfg.getValueString(TextAreaElement.KEY_VALUE);
        if (value != null) textArea.setText(value);
        textArea.textProperty().addListener((observable, oldValue, newValue) -> {
            logger.debug("Field value is changing. [oldValue: {}] [newValue: {}]", oldValue, newValue);
            if (!newValue.equals(cfg.getValueString(TextAreaElement.KEY_VALUE))) {
                cfg.setValue(TextAreaElement.KEY_VALUE, newValue);
            }
        });

        vbox.getChildren().addAll(label, textArea);
        hbox.getChildren().add(vbox);

    }

    @Override
    public Node getJavaFXNode() {
        return hbox;
    }

    @Override
    public void valueUpdated(EO eo, String key, Serializable oldValue, Serializable newValue) {
        logger.debug("Inbound value event. [newValue: {}]", newValue);
        if (TextAreaElement.KEY_VALUE.equals(key) && !textArea.getText().equals(newValue)) {
            textArea.setText(Snavig.convertToString(newValue));
        }
    }
}
