package org.hirw.game;

import static org.lwjgl.opengl.GL20.*;

import lombok.Getter;
import lombok.Setter;
import org.hirw.game.util.Log;
import org.hirw.game.util.Time;

public class FaderShader extends Shader {
  private static final String FADER_SHADER_FRAG_PATH = "assets/shaders/fader.frag.glsl";
  private static final float DEFAULT_ALPHA_INCREASE_STEP = 1.0f / 3;
  private final float INITIAL_ALPHA = 0.0f;

  @Getter private final float alphaIncreaseStep;
  @Getter @Setter private float alpha;
  @Getter @Setter private int alphaUniformLocation;

  public FaderShader(float alphaIncreaseStep) {
    super(FADER_SHADER_FRAG_PATH, DEFAULT_VERT_PATH);
    this.alpha = INITIAL_ALPHA;
    this.alphaIncreaseStep = alphaIncreaseStep;
  }

  public FaderShader() {
    this(DEFAULT_ALPHA_INCREASE_STEP);
  }

  public void init() {
    super.init();
    findAlphaUniformLocation();
  }

  public void update() {
    super.update();
    increaseAlpha();
  }

  private void findAlphaUniformLocation() {
    int location = glGetUniformLocation(getShaderProgramID(), "u_alpha");
    if (location == -1) {
      Log.warning("FaderShader", "Failed to get 'u_alpha' uniform location, trying to continue...");
    } else {
      setAlphaUniformLocation(location);
    }
  }

  private void increaseAlpha() {
    if (getAlphaUniformLocation() == -1) return;
    if (getAlpha() >= 1.0f) return;

    setAlpha(getAlpha() + (getAlphaIncreaseStep() * Time.deltaTime()));

    glUseProgram(getShaderProgramID());
    glUniform1f(getAlphaUniformLocation(), getAlpha());
    glUseProgram(0);
  }
}
