package eu.jonahbauer.wizard.client.libgdx.actions.overlay;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import eu.jonahbauer.wizard.client.libgdx.actors.PadOfTruth;
import eu.jonahbauer.wizard.client.libgdx.screens.GameScreen;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;
import java.util.stream.IntStream;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.run;

public class MakePredictionOverlay extends Overlay implements InteractionOverlay {

    private final int[] values;
    private final TextButton[] buttons;

    private final @NotNull PadOfTruth padOfTruth;

    public MakePredictionOverlay(@NotNull GameScreen gameScreen, long timeout, int round) {
        this(gameScreen, timeout, IntStream.range(0, round + 2).toArray());
    }

    protected MakePredictionOverlay(@NotNull GameScreen gameScreen, long timeout, int[] values) {
        super(gameScreen, timeout);
        this.values = values;
        this.buttons = new TextButton[values.length];
        this.padOfTruth = Objects.requireNonNull(gameScreen.getPadOfTruth());
    }

    @Override
    public VerticalGroup createContent() {
        var root = new VerticalGroup().columnCenter().space(10);

        var prompt = new Label(messages.get("game.overlay.make_prediction.prompt"), skin);
        var buttonGroup = new HorizontalGroup().space(20);

        var listener = new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                if (isClosing()) return;
                for (int i = 0; i < values.length; i++) {
                    if (actor == buttons[i]) {
                        screen.onPredictionMade(values[i]);
                        break;
                    }
                }
            }
        };

        for (int i = 0; i < values.length; i++) {
            buttons[i] = new TextButton(String.valueOf(values[i]), skin);
            buttons[i].addListener(listener);
            buttonGroup.addActor(buttons[i]);
        }

        root.addActor(prompt);
        root.addActor(buttonGroup);

        return root;
    }

    @Override
    protected void show(Group parent) {
        super.show(parent);

        padOfTruth.addAction(run(() -> screen.getOverlayRoot().addActor(padOfTruth)));
    }

    @Override
    protected void onClosing() {
        super.onClosing();

        padOfTruth.addAction(run(() -> screen.getContentRoot().addActor(padOfTruth)));
    }
}