package view.custom;

import javax.swing.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Source: <url>https://stackoverflow.com/questions/14892515/how-to-enforce-at-least-one-checkbox-in-a-group-is-selected</url>
 * <p>
 * A ButtonGroup for check-boxes enforcing that at least two remains selected.
 * <p>
 * When the group has exactly two buttons, deselecting the last selected one
 * automatically selects the other.
 * <p>
 * When the group has more buttons, deselection of the last selected one is denied.
 */
public class ButtonGroupAtLeastTwo extends ButtonGroup {

    private final Set<ButtonModel> selected = new HashSet<>();

    @Override
    public void setSelected(ButtonModel model, boolean b) {
        if (b && !this.selected.contains(model)) {
            select(model, true);
        } else if (!b && this.selected.contains(model)) {
            if (this.buttons.size() == 3 && this.selected.size() == 2) {
                select(model, false);

                AbstractButton otherOne = this.buttons.get(0).getModel() == model ?
                        this.buttons.get(1) : this.buttons.get(0);

                AbstractButton otherTwo = this.buttons.get(1).getModel() == model ?
                        this.buttons.get(2) : this.buttons.get(1);

                AbstractButton otherThree = this.buttons.get(2).getModel() == model ?
                        this.buttons.get(1) : this.buttons.get(2);


                select(otherOne.getModel(), true);
                select(otherTwo.getModel(), true);
                select(otherThree.getModel(), true);
            } else if (this.selected.size() > 2) {
                this.selected.remove(model);
                model.setSelected(false);
            }
        }
    }

    private void select(ButtonModel model, boolean b) {
        if (b) {
            this.selected.add(model);
        } else {
            this.selected.remove(model);
        }
        model.setSelected(b);
    }

    @Override
    public boolean isSelected(ButtonModel m) {
        return this.selected.contains(m);
    }

    public void addAll(AbstractButton... buttons) {
        for (AbstractButton button : buttons) {
            add(button);
        }
    }

    @Override
    public void add(AbstractButton button) {
        if (button.isSelected()) {
            this.selected.add(button.getModel());
        }
        super.add(button);
    }
}