package leigh.elements.jfoenix.type1;

import com.jfoenix.controls.JFXDatePicker;
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.DateFieldElement;
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 java.io.Serializable;
import java.time.LocalDate;

public class DateFieldElementJFoenix extends ElementBase implements ElementJFX, EOListener {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(DateFieldElementJFoenix.class);
    private HBox hbox = new HBox();
    private JFXDatePicker datePicker = new JFXDatePicker();
    private VBox vbox = new VBox();
    // Whether we should ignore the next change event. We do this to avoid a loop.

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

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

        datePicker.getStyleClass().add("vds-field-date");


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

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

        String value = cfg.getValueString(DateFieldElement.KEY_VALUE);
        if (value != null) datePicker.setValue(LocalDate.parse(value));
        datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            logger.debug("Field value is changing. [oldValue: {}] [newValue: {}]", oldValue, newValue);
            if (!newValue.equals(cfg.getValueString(DateFieldElement.KEY_VALUE))) {
                cfg.setValue(DateFieldElement.KEY_VALUE, newValue.toString());
            }
        });

        vbox.getChildren().addAll(label, datePicker);
        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 (DateFieldElement.KEY_VALUE.equals(key) && !datePicker.getValue().equals(newValue)) {
            datePicker.setValue(LocalDate.parse(String.valueOf(newValue)));
        }
    }
}
