package leigh.elements.javafx.type1;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Button;
import leigh.elements.ElementBase;
import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.actions.ScreenAction;
import leigh.elements.sdk.type1.ButtonElement;
import leigh.elements.sdk.type1.TextFieldElement;
import leigh.eo.EO;
import leigh.eo.EOListener;
import leigh.mecha.lang.FutureResult;
import leigh.mecha.lang.FutureResultListener;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.Serializable;

public class ButtonElementJFX extends ElementBase implements ElementJFX, EOListener {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ButtonElementJFX.class);
    private final AppScreenInstance screen;

    protected ButtonElementJFX(EO cfg, AppScreenInstance screen) {
        super(cfg);
        this.screen = screen;
    }

    @Override
    public Node getJavaFXNode() {
        Button btn = new Button(getCfg().getValueString(ButtonElement.KEY_LABEL));
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                EO actions = getCfg().getValueLoop(ButtonElement.KEY_ACTIONS).get(0);
                logger.info("Button clicked. [actions: {}]", actions);
                if (actions != null) {
                    String cmdFunc = actions.getValueString(TextFieldElement.KEY_ACTION_FUNC);
                    String cmdTarget = actions.getValueString(TextFieldElement.KEY_ACTION_FUNC_TARGET);
                    FutureResult<ScreenAction> future = screen.call(cmdTarget, cmdFunc);
                    future.addListener(new FutureResultListener() {
                        @Override
                        public void receiveResult(Object result) {
                            screen.processAction((ScreenAction) result);
                        }
                    });
                } else {
                    logger.warn("Button action was null.");
                }
            }
        });
        return btn;
    }

    @Override
    public void valueUpdated(EO eo, String key, Serializable oldValue, Serializable newValue) throws Exception {

    }
}
