package pathgame.rendering;

import me.hammerle.snuviengine.api.Renderer;
import me.hammerle.snuviengine.api.Texture;
import pathgame.gameplay.Player;
import pathgame.tilemap.TileMap;

public class PlayerRenderer
{
    private static final Texture CHARACTER = new Texture("resources/character.png");

    public void renderTick(TileMap map, TileMapRenderer mapR, Renderer r, Player p, float lag, float offX, float offY)
    {
        float playerSize = mapR.getScale() * TileRenderer.TILE_SIZE;

        r.setMixColorEnabled(false);
        r.setColorEnabled(false);
        r.setTextureEnabled(true);

        r.translateTo(0.0f, 0.0f);
        r.updateMatrix();

        //TODO: insert animations
        float yIndex;
        float baseX = (p.getLastX() + (p.getX() - p.getLastX()) * lag);
        float ix = baseX * mapR.getScale() * TileRenderer.TILE_SIZE + offX;

        float baseY = (p.getLastY() + (p.getY() - p.getLastY()) * lag);
        float iy = baseY * mapR.getScale() * TileRenderer.TILE_SIZE + offY;

        baseX = baseX - (int) baseX;
        baseY = baseY - (int) baseY;

        int tIndex = 0;

        CHARACTER.bind();
        if(p.getVelX() > 0)
        {
            //go right
            yIndex = 2;
            tIndex = checkForAnimationIndex(baseX, 2);
        }
        else if(p.getVelX() < 0)
        {
            //go left
            yIndex = 1;
            tIndex = checkForAnimationIndex(baseX, 2);
        }
        else if(p.getVelY() > 0)
        {
            //go down
            yIndex = 0;
            tIndex = checkForAnimationIndex(baseY, 2);
        }
        else if(p.getVelY() < 0)
        {
            //go up
            yIndex = 3;
            tIndex = checkForAnimationIndex(baseY, 2);
        }
        else
        {
            //stand still
            yIndex = 0;
        }
        r.getTextureRenderer().drawRectangle(ix, iy, ix + playerSize, iy + playerSize,
                tIndex * 0.25f, yIndex * 0.25f, (tIndex + 1) * 0.25f, yIndex * 0.25f + 0.25f);
    }

    private int checkForAnimationIndex(float base, int speed)
    {
        return (int) (Math.ceil(base / (0.125f / speed)) / 3)%4;
    }
}
