package fabrik.simulator.pic16f84;


import fabrik.simulator.pic16f84.frontendspecifics.FrontendSpecificObject;
import fabrik.simulator.pic16f84.frontendspecifics.ToggleButtonGroup;
import fabrik.simulator.pic16f84.interfaces.ToggleButtonInterface;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.input.MouseEvent;

import java.io.IOException;

public class ToggleButtonGroupExt extends PICComponent implements ToggleButtonInterface, FrontendSpecificObject {


    private static ToggleButtonGroupExt me;

    public ToggleButtonGroupExt() {
    }


    public void addAlwaysOneSelectedSupport(final ToggleButtonGroup toggleGroup) {
        toggleGroup.getToggles().addListener((ListChangeListener.Change<? extends Toggle> c) -> {
            while (c.next()) {
                for (final Toggle addedToggle : c.getAddedSubList()) {
                    addConsumeMouseEventfilter(addedToggle);
                }
            }
        });
        toggleGroup.getToggles().forEach(this::addConsumeMouseEventfilter);
    }

    private void addConsumeMouseEventfilter(Toggle toggle) {
        ((ToggleButton) toggle).addEventFilter(MouseEvent.MOUSE_PRESSED, consumeMouseEventfilter);
        ((ToggleButton) toggle).addEventFilter(MouseEvent.MOUSE_RELEASED, consumeMouseEventfilter);
        ((ToggleButton) toggle).addEventFilter(MouseEvent.MOUSE_CLICKED, consumeMouseEventfilter);
    }

    public EventHandler<MouseEvent> consumeMouseEventfilter = (MouseEvent mouseEvent) -> {
        if (((Toggle) mouseEvent.getSource()).isSelected()) {
            ToggleButtonGroup parent = (ToggleButtonGroup) ((ToggleButton) mouseEvent.getSource()).getParent();
            if (parent.getId().contains("TRIS")) {
                try {
                    ioPorts.setTRISfromUI(parent);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            else {
                try {
                    ioPorts.setPORTfromUI(parent);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            mouseEvent.consume();
        }
    };


    public void initialize(PICComponentLocator locator) {
        System.out.println("ToggleButtonGroupExt");
        super.initialize(locator);
    }
}
