/* 
 * File:   first.cpp
 * Author: sara
 *
 * Created on December 30, 2013, 11:41 AM
 */

#include <cstdlib>
/* Include the JSAPI header file to get access to SpiderMonkey. */
#include "jsapi.h"
#include <pthread.h>

using namespace std;
struct thread_parameter
{
 // char *uncompiledScript;
   // JSObject *sharedGlobalObject;
   // JSRuntime *currRt;
    char *tempstr;
   

};
/* The class of the global object. */
JSRuntime *rt;
JSObject  *global;
static JSClass global_class = {
    "global", JSCLASS_GLOBAL_FLAGS,
    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
    JSCLASS_NO_OPTIONAL_MEMBERS
};

/* The error reporter callback. */
void reportError(JSContext *cx, const char *message, JSErrorReport *report)
{
    fprintf(stderr, "%s:%u:%s\n",
            report->filename ? report->filename : "<no filename=\"filename\">",
            (unsigned int) report->lineno,
            message);
}
/** the function which the thread executes when is created at main 
 *@parameter structure of all the argument the function needs
 *@return return null at the end 
*/ 
void *threadFunction(void* arg){
 /* indicates that the execution of the script is executed successfully or not*/
 bool execute;
 int temp = 1;
// char *script = "'Hi' + 'Sara'";
 char threadScript[] = "'Hi ' + 'Sara!'";
 char *scr = threadScript;
  JSString *outStr;
/* carries the value of the last expression of the script*/
 jsval rval1;
 
/* The new context which is created by the thread*/
  JSContext *currContext;
/* pass the incoming argument of the function */
// struct thread_parameter *arg1 = (struct thread_parameter *) arg;
//const char *uncScript = (const char*)arg->uncompiledScript;
  //scr = (char *)arg;
/*Creates new context to be attached to the creator thread*/ 
currContext = JS_NewContext(rt, 8192);
  if (currContext == NULL)
       return NULL;
/* In a thread safe build every entry to the api that uses
   context must be in a request for thread safety*/
  JS_BeginRequest(currContext);
   JS_SetOptions(currContext, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
   JS_SetVersion(currContext, JSVERSION_LATEST);
/*Compiles the incoming script*/
  JSObject *compiledScript = JS_CompileScript(currContext, global, scr,strlen(scr), "threadFilename", 0);
/*Executes the compiled script*/
   execute = JS_ExecuteScript(currContext, global, compiledScript, &rval1);
      if ( rval1 == JS_FALSE)//rval == JS_NULL |
        return NULL;
    /*gets the returned value of the last expression of the executed script*/
    outStr = JS_ValueToString(currContext, rval1);
    printf("%s\n", JS_EncodeString(currContext, outStr));
/*Ends the request */
    JS_EndRequest(currContext);
/*Destroy the context of that thread*/
     JS_DestroyContext(currContext);
 //printf("HI, Sara");
    return NULL;
    
}
/*
 * 
 */
int main(int argc, const char *argv[]) {

     /* JSAPI variables. */
    //JSRuntime *rt;
    JSContext *cx;
   // JSObject  *global;
/* id of the created thread*/
    pthread_t thread_id;

    /* Create a JS runtime. You always need at least one runtime per process. */
    rt = JS_NewRuntime(8 * 1024 * 1024);
    if (rt == NULL)
        return 1;

    /* 
     * Create a context. You always need a context per thread.
     * Note that this program is not multi-threaded.
     This thread is used by the main thread only
     */
    cx = JS_NewContext(rt, 8192);
    if (cx == NULL)
        return 1;
    JS_BeginRequest(cx);
    JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
    JS_SetVersion(cx, JSVERSION_LATEST);
    JS_SetErrorReporter(cx, reportError);

    /*
     * Create the global object in a new compartment.
     * You always need a global object per context.
     */
    
    global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
    if (global == NULL)
        return 1;

    /*
     * Populate the global object with the standard JavaScript
     * function and object classes, such as Object, Array, Date.
     */
    if (!JS_InitStandardClasses(cx, global))
        return 1;

    /* Your application code here. This may include JSAPI calls
     * to create your own custom JavaScript objects and to run scripts.
     *
     * The following example code creates a literal JavaScript script,
     * evaluates it, and prints the result to stdout.
     *
     * Errors are conventionally saved in a JSBool variable named ok.
     */


    /** Create the thread here....*/
    struct thread_parameter threadArg;
    //threadArg.sharedGlobalObject = global;
     char threadScript[] = "'Hi ' + 'Sara!'";
    //threadArg.tempstr = threadScript;
    //threadArg.currRt = rt;
   
    pthread_create(&thread_id, NULL, &threadFunction,NULL);
/*****************************************************************/
    const char *script = "'Hello ' + 'World!'";
    jsval rval;
    JSString *str;
    JSBool ok;
    const char *filename = "noname";
    uintN lineno = 0;
    ok = JS_EvaluateScript(cx, global, script, strlen(script),
                           filename, lineno, &rval);
    if ( rval == JS_FALSE)//rval == JS_NULL |
        return 1;
    str = JS_ValueToString(cx, rval);
    printf("%s\n", JS_EncodeString(cx, str));

    /* End of your application code */

    /* Clean things up and shut down SpiderMonkey. */
    JS_EndRequest(cx);
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    
    return 0;
}

