/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <jni.h>
#include <errno.h>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>

#include "android_port.h"
#include "osmroute.h"
#include "gui.h"
#include "system.h"

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "sposmroute", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "sposmroute", __VA_ARGS__))

#define MAX_EVENTS 128
GUIEvent eventlist[MAX_EVENTS] = {0};
int eventcnt = 0;

int gevent_push (GUIEvent *event);
int gevent_pop (GUIEvent *event);
void gevent_clear ();

struct engine engine;

/**
 * Initialize an EGL context for the current display.
 */
static int engine_init_display(struct engine* engine) {
    const EGLint attribs[] = {
            EGL_SURFACE_TYPE, 
  			EGL_WINDOW_BIT, 
  			EGL_RENDERABLE_TYPE,
            EGL_OPENGL_ES2_BIT,
            EGL_BLUE_SIZE, 8,
            EGL_GREEN_SIZE, 8,
            EGL_RED_SIZE, 8,
            EGL_NONE
    };
    EGLint w, h, dummy, format;
    EGLint numConfigs;
    EGLConfig config;
    EGLSurface surface;
    EGLContext context;

	const EGLint contextAttrs[] = {
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};
    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    eglInitialize(display, 0, 0);

    /* Here, the application chooses the configuration it desires. In this
     * sample, we have a very simplified selection process, where we pick
     * the first EGLConfig that matches our criteria */
    eglChooseConfig(display, attribs, &config, 1, &numConfigs);

    /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
     * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
     * As soon as we picked a EGLConfig, we can safely reconfigure the
     * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
    eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

    ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);

    surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
    context = eglCreateContext(display, config, NULL, contextAttrs);

    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
        LOGW("Unable to eglMakeCurrent");
        return -1;
    }

    eglQuerySurface(display, surface, EGL_WIDTH, &w);
    eglQuerySurface(display, surface, EGL_HEIGHT, &h);

    engine->display = display;
    engine->context = context;
    engine->surface = surface;
    engine->width = w;
    engine->height = h;
    engine->state.angle = 0;
	gfx_init (w, h);
    return 0;
}


/**
 * Tear down the EGL context currently associated with the display.
 */
static void engine_term_display(struct engine* engine) {
    if (engine->display != EGL_NO_DISPLAY) {
        eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        if (engine->context != EGL_NO_CONTEXT) {
            eglDestroyContext(engine->display, engine->context);
        }
        if (engine->surface != EGL_NO_SURFACE) {
            eglDestroySurface(engine->display, engine->surface);
        }
        eglTerminate(engine->display);
    }
    engine->animating = 0;
    engine->display = EGL_NO_DISPLAY;
    engine->context = EGL_NO_CONTEXT;
    engine->surface = EGL_NO_SURFACE;
}

/**
 * Process the next input event.
 * save events inside a EVENT list.
 */
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
	GUIEvent gevent;
	int32_t type = AInputEvent_getType(event);
	
    struct engine* engine = (struct engine*)app->userData;
    if (type == AINPUT_EVENT_TYPE_MOTION) {
		int32_t subtype = AMotionEvent_getAction (event);
		gevent.scr_mpos.x = AMotionEvent_getX(event, 0);
		gevent.scr_mpos.y = AMotionEvent_getY(event, 0);
			
		if (subtype == AMOTION_EVENT_ACTION_MOVE) {
			gevent.event = EGUI_MOUSEMOVE;
			gevent_push (&gevent);
			return 1;
		}
		else if (subtype == AMOTION_EVENT_ACTION_UP) {
			gevent.mousebtn = 1;
			gevent.event = EGUI_MOUSERELEASED;
			gevent_push (&gevent);
			return 1;
		}
		else if (subtype == AMOTION_EVENT_ACTION_DOWN) {
			char *tmp;
			gevent.mousebtn = 1;
			gevent.event = EGUI_MOUSEPRESSED;
			gevent_push (&gevent);
			return 1;
		}
    }
	
    return 0;
}

/**
 * Process the next main command.
 */
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
    switch (cmd) {
        case APP_CMD_SAVE_STATE:
            // The system has asked us to save our current state.  Do so.
			d_printf ("APP_CMD_SAVE_STATE");
            engine.app->savedState = malloc(sizeof(struct saved_state));
            *((struct saved_state*)engine.app->savedState) = engine.state;
            engine.app->savedStateSize = sizeof(struct saved_state);
            break;
        case APP_CMD_INIT_WINDOW:
            // The window is being shown, get it ready.
			d_printf ("APP_CMD_INIT_WINDOW");
            if (engine.app->window != NULL) {
                engine_init_display(&engine);
			    if (engine.display == NULL) {
			        // No display.
			        return;
			    }
//				test_draw ();
				draw ();
            }
            break;
        case APP_CMD_TERM_WINDOW:
            // The window is being hidden or closed, clean it up.
			d_printf ("APP_CMD_TERM_WINDOW");
            engine_term_display(&engine);
			app_shutdown ();		// we quit when we terminate the window...
			exit (1);
            break;
        case APP_CMD_GAINED_FOCUS:
            // When our app gains focus, we start monitoring the accelerometer.
			d_printf ("APP_CMD_GAINED_FOCUS");
            if (engine.accelerometerSensor != NULL) {
                ASensorEventQueue_enableSensor(engine.sensorEventQueue,
                        engine.accelerometerSensor);
                // We'd like to get 60 events per second (in us).
                ASensorEventQueue_setEventRate(engine.sensorEventQueue,
                        engine.accelerometerSensor, (1000L/60)*1000);
            }
            break;
        case APP_CMD_LOST_FOCUS:
            // When our app loses focus, we stop monitoring the accelerometer.
            // This is to avoid consuming battery while not being used.
			d_printf ("APP_CMD_LOST_FOCUS");
            if (engine.accelerometerSensor != NULL) {
                ASensorEventQueue_disableSensor(engine.sensorEventQueue,
                        engine.accelerometerSensor);
            }
            // Also stop animating.
            engine.animating = 0;
//			test_draw ();
			draw ();
            break;
		case APP_CMD_STOP:
			d_printf ("APP_CMD_STOP");
			break;
		case APP_CMD_START:
			d_printf ("APP_CMD_START");
			break;
		case APP_CMD_PAUSE:
			d_printf ("APP_CMD_PAUSE");
			break;
		case APP_CMD_RESUME:
			d_printf ("APP_CMD_RESUME");
			break;
    }
}


void main_event () {
    // Read all pending events.
    time_t t1 = time(NULL), t2 = time(NULL);
	struct gps_data *gpspos;
    int ident;
    int events;
    int t = 0;
    GUIEvent event;
    struct android_poll_source* source;

    // If not animating, we will block forever waiting for events.
    // If animating, we loop until all events are read, then continue
    // to draw the next frame of animation.
    while ((ident=ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0) {
        // Process this event.
        if (source != NULL) {
            source->process(engine.app, source);
        }

        // If a sensor has data, process it now.
        if (ident == LOOPER_ID_USER) {
            if (engine.accelerometerSensor != NULL) {
                ASensorEvent event;
                while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
                        &event, 1) > 0) {
//                        LOGI("accelerometer: x=%f y=%f z=%f",
//                                event.acceleration.x, event.acceleration.y,
//                                event.acceleration.z);
                }
            }
        }

        // Check if we are exiting.
        if (engine.app->destroyRequested != 0) {
            engine_term_display(&engine);
            return;
        }
    }
    while (gevent_pop(&event)) {
    	gui_event (event);
    }

    t1 = time(NULL);
    if (t1 != t2) {
    	t2 = t1;
		app_loop ();
   }
}

/**
 * This is the main entry point of a native application that is using
 * android_native_app_glue.  It runs in its own thread, with its own
 * event loop for receiving input events and doing other things.
 */
void android_main(struct android_app* state) {
    // Make sure glue isn't stripped.
    app_dummy();

	d_printf ("Android Version");
    memset(&engine, 0, sizeof(engine));
    state->userData = &engine;
    state->onAppCmd = engine_handle_cmd;
    state->onInputEvent = engine_handle_input;
    engine.app = state;

	d_printf ("internal data path: %s", state->activity->internalDataPath);
	d_printf ("external data path: %s", state->activity->externalDataPath);

    // Prepare to monitor accelerometer
    engine.sensorManager = ASensorManager_getInstance();
    engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
            ASENSOR_TYPE_ACCELEROMETER);
    engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
            state->looper, LOOPER_ID_USER, NULL, NULL);

    if (state->savedState != NULL) {
        // We are starting with a previous saved state; restore from it.
        engine.state = *(struct saved_state*)state->savedState;
    }

	app_init (0, NULL);

    // loop waiting for stuff to do.
    while (app.status != APPSTATUS_quit) {
    	main_event ();
    }
    d_printf ("shutdown?");
	app_shutdown ();
	exit (0);
}



/*************************************************************************
 * main functions for sposmroute...
 */
void main_wnd_update () {
	main_event ();
}



/*************************************************************************
 *
 * calling java code here for using the internal GPS devices.
 *
 *************************************************************************/

int gps_android_device_open () {
	d_printf ("gps_android_device_open:");
	ANativeActivity* activity = engine.app->activity;
	JavaVM* jvm = engine.app->activity->vm;
	JNIEnv* env = NULL;
	(*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6);
	jint res = (*jvm)->AttachCurrentThread(jvm, &env, NULL);
	if (res == JNI_ERR) {
		// Failed to retrieve JVM environment
		d_printf ("gps_android_device_open: JNI_Error");
		return 0;
	}
	jclass clazz = (*env)->GetObjectClass(env, activity->clazz);
	jmethodID methodID = (*env)->GetMethodID(env, clazz, "GPSDataStart", "()V");
	(*env)->CallVoidMethod(env, activity->clazz, methodID);
	(*jvm)->DetachCurrentThread(jvm);
	return 1;
};

void gps_android_device_close () {
	d_printf ("gps_android_device_close:");
	ANativeActivity* activity = engine.app->activity;
	JavaVM* jvm = engine.app->activity->vm;
	JNIEnv* env = NULL;
	(*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6);
	jint res = (*jvm)->AttachCurrentThread(jvm, &env, NULL);
	if (res == JNI_ERR) {
		// Failed to retrieve JVM environment
		d_printf ("gps_android_device_close: JNI_Error");
		return;
	}

	jclass clazz = (*env)->GetObjectClass(env, activity->clazz);
	jmethodID methodID = (*env)->GetMethodID(env, clazz, "GPSDataStop", "()V");
	(*env)->CallVoidMethod(env, activity->clazz, methodID);
	(*jvm)->DetachCurrentThread(jvm);
	return;
};

int gps_android_device_read (char *ptr, int ptrsize) {
	ANativeActivity* activity = engine.app->activity;
	JavaVM* jvm = engine.app->activity->vm;
	JNIEnv* env = NULL;
	jstring jstr;
	const char *str;

	d_printf ("gps_android_device_read:");

	(*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6);
	jint res = (*jvm)->AttachCurrentThread(jvm, &env, NULL);
	if (res == JNI_ERR) {
		// Failed to retrieve JVM environment
		d_printf ("gps_android_device_read: JNI_Error");
		return 0;
	}

	/* call up the java method to prepare a new line */
	jclass clazz = (*env)->GetObjectClass(env, activity->clazz);
	jmethodID methodID = (*env)->GetMethodID(env, clazz, "GPSDataGetLine", "()V");
	(*env)->CallVoidMethod(env, activity->clazz, methodID);
	/* retrieve the new line, copy new line, release new line */
	jfieldID fid = (*env)->GetFieldID(env, clazz, "gpsline", "Ljava/lang/String;");
	jstr = (*env)->GetObjectField(env, activity->clazz, fid);
	str = (*env)->GetStringUTFChars(env, jstr, 0);
	if (str != NULL) {
//		d_printf ("str:ptrsize:%d  strsize:%d    '%s'", ptrsize, strlen(str), str);
		strncpy (ptr, str, ptrsize);
	}
	else ptr[0] = 0;
	(*env)->ReleaseStringUTFChars(env, jstr, str);
	(*jvm)->DetachCurrentThread(jvm);

	return strlen (ptr);
};


int gevent_push (GUIEvent *event) {
	if (eventcnt < MAX_EVENTS) {
		memcpy (&eventlist[eventcnt], event, sizeof (GUIEvent));
		eventcnt++;
		return 1;
	}
	return 0;
};


int gevent_pop (GUIEvent *event) {
	if (eventcnt > 0) {
		eventcnt--;
		memcpy (event, &eventlist[eventcnt], sizeof (GUIEvent));
		return 1;
	}
	return 0;
};

void gevent_clear () {
	int i;

	memset (eventlist, 0x0, MAX_EVENTS * sizeof (GUIEvent));
};

