#include <iostream>
#include <windows.h>
#include <jni.h>

#pragma comment(lib, "jvm.lib")

using namespace std;


void main(){

	cout<<"JVM Create Start!!"<<endl;

	// JavaVM create & JVM environment setting start
	JavaVMOption options[1];
	JavaVMInitArgs vm_args;
	JNIEnv *env;
	JavaVM *jvm;
	long status;
	
	options[0].optionString = "-Djava.class.path=.";
	memset(&vm_args, 0, sizeof(vm_args));
	vm_args.version = JNI_VERSION_1_6;
	vm_args.nOptions = 1;
	vm_args.options = options;
	status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
	// JavaVM create & JVM environment setting end
	
	cout<<"JVM Operating......."<<endl;

	cout<<"\n10과 20의 합을 알아보겠습니다.\n"<<endl;

	jclass cls;
	jmethodID mid;
	jobject obj;
	int staticresult=0;
	int result=0;

	if(status != JNI_ERR)
	{
		cls = env->FindClass("FirstJavaEx");
		
		if(cls != 0)
		{
			//
			// Use the static method start
			//
			cout<<"\t'static'함수 호출 시작" << endl;
			mid = env->GetStaticMethodID(cls, "staticAdd", "(II)I");
			if (mid != 0)
			{
				staticresult = env->CallStaticIntMethod(cls, mid, 10, 20);
				cout<<"\t'static'함수 호출 결과: " << staticresult << endl;
			}
			else
			{
				printf("mid error\n");
				return;
			}
			//
			// Use the static method end
			//
			
			//
			//Create the Instance of InvokeFirstEX Class start
			//
			cout<<"\n\tInvokeFirstEx 클래스의 인스턴스 생성" << endl;
			jmethodID cls_constructor = env->GetMethodID(cls, "<init>", "()V");
			
			if (cls_constructor != 0) {				
				obj = env->NewObject(cls, cls_constructor, "()V");
				cout<<"\t\t함수 호출 시작" << endl;
				mid = env->GetMethodID(cls, "AddFunc", "(II)I"); 
				if (mid != 0)
				{
					result = env->CallIntMethod(obj, mid, 10, 20);
					cout<<"\t\t함수 호출 결과: " << result << endl;
				}
				else
				{
					printf("mid error\n");
					return;
				}
			}		
		}
		else 
		{
			printf("Can't find class\n");
			return;
		}
		
		jvm->DestroyJavaVM();
		cout<<"\nJVM Destroyed!!"<<endl;
	}
	
}
