package leigh.elements.jfoenix.type1;

import com.jfoenix.controls.JFXColorPicker;
import javafx.scene.Node;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import leigh.elements.ElementBase;
import leigh.elements.javafx.type1.ElementJFX;
import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.type1.ColorFieldElement;
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;

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

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

        cp.setPromptText(cfg.getValueString(ColorFieldElement.KEY_LABEL));

        cp.getStyleClass().add("vds-field-color");

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

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

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

        hbox.getChildren().add(cp);

    }

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

    @Override
    public void valueUpdated(EO eo, String key, Serializable oldValue, Serializable newValue) {
        logger.info("Inbound value event. [newValue: {}]", newValue);
        if (ColorFieldElement.KEY_VALUE.equals(key) && !cp.getValue().equals(newValue)) {
            cp.setValue(convertToColor(newValue));
        }
    }

    public static Color convertToColor(Object value) {
        if (value == null) return null;
        String s = String.valueOf(value);
        if (s == null || s.isEmpty()) return null;
        return Color.web(s, 1.0);
    }

}
