package pathgame.gameplay.menu;

import pathgame.gameplay.Gamestate;
import pathgame.gameplay.Keys;

public abstract class BaseMenu
{
    private final int id;
    private int index = 0;
    public abstract MenuOption[] getOptions();
    private int returnId;
    
    public BaseMenu(int id)
    {
        this.id = id;
    }
    
    public int getActiveIndex()
    {
        return index;
    }
    
    public boolean isOptionMenu()
    {
        return false;
    }
    
    public int tick(Gamestate gamestate)
    {
        returnId = id;
        if(isUpPressed())
        {
            int length = getOptions().length;
            index = ((index - 1) + length) % length;
        }
        else if(isDownPressed())
        {
            index = (index + 1) % getOptions().length;
        }
        else if(isEnterPressed())
        {
            getOptions()[index].run(gamestate);
        }
        if(returnId != id)
        {
            index = 0;
        }
        return returnId;
    }
    
    public void setReturnId(int id)
    {
        returnId = id;
    }
            
    private boolean isUpPressed()
    {
        return Keys.UP_KEY.isDown() && Keys.UP_KEY.getTime() == 1 || (Keys.UP_KEY.getTime() >= 20 && Keys.UP_KEY.getTime() % 5 == 1);
    }
    
    private boolean isDownPressed()
    {
        return Keys.DOWN_KEY.isDown() && Keys.DOWN_KEY.getTime() == 1 || (Keys.DOWN_KEY.getTime() >= 20 && Keys.DOWN_KEY.getTime() % 5 == 1);
    }
    
    private boolean isEnterPressed()
    {
        return Keys.CONFIRM_KEY.isDown() && Keys.CONFIRM_KEY.getTime() == 1;
    }
    
    public void resetIndex()
    {
        index = 0;
    }
}