package gov.nasa.jpl.issm.visual;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;


class MyGLSurfaceView extends GLSurfaceView 
{
	private MyGLRenderer mRend;
    public MyGLSurfaceView(Context context) 
    {
        super(context);

        // Create an OpenGL ES 2.0 context.
        setEGLContextClientVersion(2);
        
        final int NMAX_TRIANGLES = 2000;
        final int MAX_VERTICES = 21;
        
        float f[][] = new float[NMAX_TRIANGLES][MAX_VERTICES];
        int n, random;
		for (int i = 0; i < f.length; i++)
		{
			for (int j = 0; j < MAX_VERTICES; j++)
			{
				if (j == 6 || j == 13 || j == 20) continue;
				n = 1;
		        random = (int)(Math.floor((Math.random()*10)+1));
		        if (random <= 5) n = -1;
		        
				f[i][j] = (float)(Math.random()*n);
			}
		}

        mRend = new MyGLRenderer(f);
        
        // Set the Renderer for drawing on the GLSurfaceView
        setRenderer(mRend);

        // Render the view only when there is a change in the drawing data
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }
    
    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
    private float mPreviousX;
    
    private float mPreviousY;
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        // MotionEvent reports input details from the touch screen
        // and other input controls. In this case, you are only
        // interested in events where the touch position changed.

        float x = e.getX();
        float y = e.getY();

        switch (e.getAction()) {
            case MotionEvent.ACTION_MOVE:

                float dx = x - mPreviousX;
                float dy = y - mPreviousY;

                // reverse direction of rotation above the mid-line
                if (y > getHeight() / 2) {
                  dx = dx * -1 ;
                }

                // reverse direction of rotation to left of the mid-line
                if (x < getWidth() / 2) {
                  dy = dy * -1 ;
                }

                mRend.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR;  // = 180.0f / 320
                requestRender();
        }

        mPreviousX = x;
        mPreviousY = y;
        return true;
    }
}