package xaero.rotatenjump.gui;

import java.util.ArrayList;
import java.util.List;

import xaero.rotatenjump.game.graphics.Graphics;
import xaero.rotatenjump.gui.elements.Button;

/**
 * Created by xaero on 11/07/2017.
 */

public abstract class ScrollableGui extends Gui {

    protected List<Button> allButtons;
    protected int offset = 0;
    protected int sizeY;
    private float lastY;
    private float velocityY;
    private boolean dragging = false;
    private float scrollStartY = -1;

    ScrollableGui(){
        super();
        allButtons = new ArrayList<>();
        lastY = -1;
        sizeY = (int)Graphics.getHeight();
    }

    @Override
    public void render(float touchX, float touchY){
        scroll(touchY);
        if(lastY == -1 && touchY != -1)
            scrollStartY = touchY;
        lastY = touchY;

        drawBackground();

        offset -= velocityY;
        int bottom = (int) (offset + Graphics.getHeight());
        int tooMuch = offset < 0 ? offset : (bottom > sizeY ? bottom - sizeY : 0);
        if(tooMuch != 0 && !dragging) {
            offset = (int) (offset - tooMuch * 0.1f);
            velocityY = 0;
            //Log.d("", "test");
        }
        if(velocityY != 0) {
            float oldVel = velocityY;
            velocityY -= Math.copySign(3, velocityY);
            if (oldVel * velocityY < 0)
                velocityY = 0;
        }

        buttons.clear();
        for(int i = 0; i < allButtons.size(); i++) {
            Button b = allButtons.get(i);
            if(b.getY() - offset < Graphics.getHeight() && b.getY() + b.getH() - offset > 0)
                buttons.add(b);
        }

        for(int i = 0; i < buttons.size(); i++)
            buttons.get(i).render(0, -offset);
    }

    @Override
    public void onTouch(float x, float y) {
        onFixedTouch(x, y + offset);
    }

    protected void onFixedTouch(float x, float y){
        super.onTouch(x, y);
    }

    protected void onFixedRelease(float x, float y){
        super.onRelease(x, y);
    }

    @Override
    public void onRelease(float x, float y) {
        lastY = -1;
        onFixedRelease(x, y + offset);
        dragging = false;
    }

    private void scroll(float y){
        if(lastY != -1){
            if(!dragging && Math.abs(y - scrollStartY) > Graphics.getHeight() / Gui.TOUCH_SLIMNESS)
                dragging = true;
            if(dragging) {
                velocityY = y - lastY;
                if (Math.abs(velocityY) > 200)
                    velocityY *= Math.abs(200 / velocityY);
            }
        }
    }
}
