package com.example.alfred.trogl;

import android.content.Context;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glViewport;
import static android.opengl.Matrix.orthoM;

public class OGLRenderer implements GLSurfaceView.Renderer {

    private final Context context;
    private static final String TAG = "BasicOGL";

    OGLTriangle triangle1;
    OGLTriangle triangle2;
    private final float[] projectionMatrix = new float[16];

    public OGLRenderer(Context context) {
        this.context = context;
    }

    @Override
    public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        String vertexShaderSource = Utils.ResourcesReader(context, R.raw.vertex);
        String fragmentShaderSource = Utils.ResourcesReader(context, R.raw.fragment_green);
        triangle1 = new OGLTriangle(vertexShaderSource, fragmentShaderSource);
        triangle1.setPosX(0.0f);
        triangle1.setPosY(0.0f);

        triangle1.setSizeX(5.0f);
        triangle1.setSizeY(5.0f);
        triangle1.setSizeZ(5.0f);

        fragmentShaderSource = Utils.ResourcesReader(context, R.raw.fragment_red);
        triangle2 = new OGLTriangle(vertexShaderSource, fragmentShaderSource);
        triangle2.setPosX(0.0f);
        triangle2.setPosY(0.2f);

        triangle1.setChild(triangle2);
    }

    @Override
    public void onSurfaceChanged(GL10 glUnused, int width, int height) {
        glViewport(0, 0, width, height);

        //MatrixHelper.perspectiveM(projectionMatrix, 45, (float) width / (float) height, 1f, 10f);
        orthoM(projectionMatrix, 0, -3.0f, 3.0f, -3.0f, 3.0f, -3.0f, 3.0f);
    }

    @Override
    public void onDrawFrame(GL10 glUnused) {
        glClear(GL_COLOR_BUFFER_BIT);
        triangle1.draw(projectionMatrix, null, null, null);
    }
}
