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

import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.I18NBundle;
import eu.jonahbauer.wizard.client.libgdx.WizardGame;
import eu.jonahbauer.wizard.client.libgdx.screens.GameScreen;
import lombok.AccessLevel;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;

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

public abstract class Overlay extends Action {
    protected final GameScreen screen;
    protected final Skin skin;
    protected final I18NBundle messages;
    protected final TextureAtlas atlas;
    private long timeout;

    private Container<?> root;
    private boolean started;
    @Getter(AccessLevel.PROTECTED)
    private boolean closing;
    private boolean closed;

    public Overlay(@NotNull GameScreen gameScreen, long timeout) {
        this.screen = gameScreen;
        this.skin = gameScreen.getSkin();
        this.messages = gameScreen.getMessages();
        this.atlas = gameScreen.getAtlas();
        this.timeout = timeout;
    }

    @Override
    public boolean act(float delta) {
        if (!started) {
            if (System.currentTimeMillis() > timeout) {
                return true;
            }

            started = true;
            show(screen.getOverlayRoot());
        }

        if (System.currentTimeMillis() > timeout && !closing) {
            closing = true;
            onClosing();
        }

        return closed;
    }

    protected abstract Actor createContent();

    protected Container<?> getRoot() {
        if (root == null) {
            root = new Container<>(createContent());
            root.setSize(WizardGame.WIDTH, WizardGame.HEIGHT);
        }

        return root;
    }

    protected void show(Group parent) {
        parent.addActor(getRoot());
    }

    protected final void onClosed() {
        if (closed) return;
        closed = true;
        getRoot().remove();
    }

    protected void onClosing() {
        getRoot().addAction(run(this::onClosed));
    }

    public void close() {
        timeout = 0;
    }
}
