package psemek.app;

import android.app.Activity;
import android.app.ActionBar;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.view.WindowInsetsController;
import android.view.WindowInsets.Type;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLES30;
import android.os.Bundle;
import java.lang.System;

public class MainActivity extends Activity {

	class RendererImpl implements Renderer {

		@Override
		public void onSurfaceCreated(GL10 gl10, EGLConfig config) {
			MainActivity.this.nativeApp.init();
		}

		@Override
		public void onSurfaceChanged(GL10 gl10, int width, int height) {
			MainActivity.this.nativeApp.resize(width, height);
		}
		
		@Override
		public void onDrawFrame(GL10 gl10) {
			MainActivity.this.nativeApp.drawFrame();
		}

	}

	class ViewImpl extends GLSurfaceView {

		private final RendererImpl renderer;

		public ViewImpl(Context context) {
			super(context);
			setEGLContextClientVersion(3);
			setEGLConfigChooser(8, 8, 8, 8, 24, 8);
			renderer = new RendererImpl();
			setRenderer(renderer);
			setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
		}

		@Override
		public boolean onTouchEvent(MotionEvent e) {
			switch (e.getActionMasked()) {
			case MotionEvent.ACTION_DOWN:
			case MotionEvent.ACTION_POINTER_DOWN:
				MainActivity.this.nativeApp.touchDown((int)e.getX(), (int)e.getY());
				return true;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_POINTER_UP:
				MainActivity.this.nativeApp.touchUp((int)e.getX(), (int)e.getY());
				return true;
			case MotionEvent.ACTION_MOVE:
				MainActivity.this.nativeApp.touchMove((int)e.getX(), (int)e.getY());
				return true;
			}
			return false;
		}

	}

	private PsemekApplication nativeApp;
	private ViewImpl view;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		System.loadLibrary("boost_random");
		System.loadLibrary("TARGET_NAME");

  		ActionBar actionBar = getActionBar();
  		if (actionBar != null) {
  			actionBar.hide();
  		}

  		nativeApp = new PsemekApplication(this.getAssets());

		view = new ViewImpl(this);
		setContentView(view);

  		WindowInsetsController windowInsetsController = view.getWindowInsetsController();
  		if (windowInsetsController != null) {
  			windowInsetsController.hide(Type.systemBars());
  			windowInsetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
  		}
	}

	@Override
	protected void onDestroy() {
		nativeApp.destroy();
		super.onDestroy();
	}

}
