#include "InterpreterV8.h"

#ifdef HAVE_SQL
#include "Database.h"
#endif

#include <boost/tokenizer.hpp>

InterpreterV8 *InterpreterV8::This = 0;

#ifdef HAVE_V8

#include <v8.h>
#include <fstream>
#include <sstream>
#include <iomanip>

using namespace std;
using namespace v8;

bool InterpreterV8::ReportException(TryCatch* try_catch)
{
    const HandleScope handle_scope;

    const String::Utf8Value exception(try_catch->Exception());

    if (*exception && string(*exception)=="exit")
        return true;

    const Handle<Message> message = try_catch->Message();

    // Print (filename):(line number): (message).
    const String::Utf8Value filename(message->GetScriptResourceName());

    ostringstream out;

    if (*filename)
        out << *filename;
    if (!message.IsEmpty())
        out << ": l." << message->GetLineNumber();
    if (*exception)
        out << ": " << *exception;

    JsException(out.str());

    if (message.IsEmpty())
        return false;

    // Print line of source code.
    const String::Utf8Value sourceline(message->GetSourceLine());
    if (*sourceline)
        JsException(*sourceline);

    // Print wavy underline (GetUnderline is deprecated).
    const int start = message->GetStartColumn();
    const int end   = message->GetEndColumn();

    out.str("");
    if (start>0)
        out << setfill(' ') << setw(start) << ' ';
    out << setfill('^') << setw(end-start) << '^';

    JsException(out.str());

    String::Utf8Value stack_trace(try_catch->StackTrace());
    if (stack_trace.length()<=0)
        return false;

    //if (*stack_trace)
    //    JsException(string("\n")+*stack_trace);

    return false;
}

// Executes a string within the current v8 context.
bool InterpreterV8::ExecuteStringNT(const Handle<String> &code, const Handle<Value> &file)
{
    if (code.IsEmpty())
        return true;

    const HandleScope handle_scope;

    const Handle<Script> script = Script::Compile(code, file);
    if (script.IsEmpty())
        return false;

    const Handle<Value> result = script->Run();
    if (result.IsEmpty())
        return false;

    // If all went well and the result wasn't undefined then print
    // the returned value.
    if (!result->IsUndefined())
        JsResult(*String::Utf8Value(result));

    return true;
}

bool InterpreterV8::ExecuteCode(const Handle<String> &code, const Handle<Value> &file)
{
    TryCatch exception;

    const bool rc = ExecuteStringNT(code, file);

    if (!exception.CanContinue())
        return false;

    if (exception.HasCaught())
        return ReportException(&exception);

    return rc;
}

bool InterpreterV8::ExecuteCode(const string &code, const string &file)
{
    return ExecuteCode(String::New(code.c_str(), code.size()),
                         String::New(file.c_str()));
}

bool InterpreterV8::ExecuteFile(const string &name)
{
    ifstream fin(name.c_str());
    if (!fin)
    {
        JsException("Error - Could not open file '"+name+"'");
        return false;
    }

    string buffer;
    if (!getline(fin, buffer, '\0'))
        return true;

    if (fin.fail())
    {
        JsException("Error - reading file.");
        return false;
    }

    return ExecuteCode(buffer, name);
}

Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
{
    if (args.Length()!=2 && args.Length()!=3)
        return ThrowException(String::New("Number of arguments must be 2 or 3."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 not a string."));

    if (!args[1]->IsInt32())
        return ThrowException(String::New("Argument 2 not an int32."));

    if (args.Length()==3 && !args[2]->IsUint32())
        return ThrowException(String::New("Argument 3 not an uint32."));

    const string   server   = *String::Utf8Value(args[0]);
    const  int32_t state    = args[1]->Int32Value();
    const uint32_t millisec = args.Length()==3 ? args[2]->Int32Value() : 0;

    const int rc = JsWait(server, state, millisec);

    if (rc==0 || rc==1)
        return Boolean::New(rc);

    return ThrowException(String::New(("Waitig for state "+to_string(state)+" of server '"+server+"' failed.").c_str()));
}

Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
{
    if (args.Length()==0)
        return ThrowException(String::New("Number of arguments must be at least 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    const HandleScope handle_scope;

    const String::Utf8Value str(args[0]);

    string command = *str;

    for (int i=1; i<args.Length(); i++)
    {
        const String::Utf8Value arg(args[i]);
        command += " \""+string(*arg)+"\"";
    }

    return Boolean::New(JsSend(command));
}

Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsUint32())
        return ThrowException(String::New("Argument 1 must be an uint32."));

    JsSleep(args[0]->Int32Value());

    return Undefined();
}

Handle<Value> InterpreterV8::FuncState(const Arguments& args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    // Return state.name/state.index

    HandleScope handle_scope;

    const String::Utf8Value str(args[0]);

    const pair<int32_t, string> rc = JsState(*str);

    Handle<ObjectTemplate> obj = ObjectTemplate::New();

    obj->Set(String::New("index"), rc.first<=-256?Undefined():Integer::New(rc.first),         ReadOnly);
    obj->Set(String::New("name"),  rc.first<=-256?Undefined():String::New(rc.second.c_str()), ReadOnly);
    //obj->Set(String::New("toString"),  String::New(("[Object state "+string(*str)+"]").c_str()), ReadOnly);

    return handle_scope.Close(obj->NewInstance());
}

Handle<Value> InterpreterV8::FuncExit(const Arguments &)
{
    v8::V8::TerminateExecution(fThreadId);
    return ThrowException(String::New("exit"));
/*
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsUint32())
        return ThrowException(String::New("Argument 1 must be an uint32."));

    const HandleScope handle_scope;

    JsSleep(args[0]->Int32Value());
*/
    return Undefined();
}

// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called.  Prints its arguments on stdout separated by
// spaces and ending with a newline.
Handle<Value> InterpreterV8::FuncPrint(const Arguments& args)
{
    for (int i=0; i<args.Length(); i++)
    {
        const HandleScope handle_scope;

        const String::Utf8Value str(args[i]);
        if (*str)
            JsPrint(*str);
    }
    return Undefined();
}

Handle<Value> InterpreterV8::FuncOut(const Arguments& args)
{
    for (int i=0; i<args.Length(); i++)
    {
        const HandleScope handle_scope;

        const String::Utf8Value str(args[i]);
        if (*str)
            JsOut(*str);
    }
    return Undefined();
}

// The callback that is invoked by v8 whenever the JavaScript 'load'
// function is called.  Loads, compiles and executes its argument
// JavaScript file.
Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
{
    for (int i = 0; i<args.Length(); i++)
    {
        const HandleScope handle_scope;

        const String::Utf8Value file(args[i]);
        if (*file == NULL)
            return ThrowException(String::New(("Error loading file '"+string(*file)+"'").c_str()));

        if (!ExecuteFile(*file))
            return ThrowException(String::New(("Execution of '"+string(*file)+"' failed").c_str()));
    }
    return Undefined();
}

Handle<Value> InterpreterV8::FuncVersion(const Arguments&)
{
    return String::New(V8::GetVersion());
}

Handle<Value> InterpreterV8::FuncDbClose(const Arguments &args)
{
    HandleScope handle_scope;

    void *ptr = Local<External>::Cast(args.This()->GetInternalField(0))->Value();
    if (!ptr)
        return Boolean::New(false);

#ifdef HAVE_SQL
    Database *db = reinterpret_cast<Database*>(ptr);
    auto it = find(fDatabases.begin(), fDatabases.end(), db);
    fDatabases.erase(it);
    delete db;
#endif

    args.This()->SetInternalField(0, External::New(0));

    return Boolean::New(true);
}
Handle<Value> InterpreterV8::FuncDbQuery(const Arguments &args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Both arguments must be a string."));

    HandleScope handle_scope;

    void *ptr = Local<External>::Cast(args.This()->GetInternalField(0))->Value();
    if (!ptr)
        return Undefined();

    const String::Utf8Value query(args[0]);

#ifdef HAVE_SQL
    try
    {
        Database *db = reinterpret_cast<Database*>(ptr);

        const mysqlpp::StoreQueryResult res = db->query(*query).store();

        Handle<Array> ret = Array::New();
        ret->Set(String::New("table"), String::New(res.table()), ReadOnly);

        Handle<Array> cols = Array::New();

        int irow=0;
        for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
        {
            Handle<Array> row = Array::New();

            const mysqlpp::FieldNames *list = it->field_list().list;

            for (size_t i=0; i<it->size(); i++)
            {
                const Handle<Value> name = String::New((*list)[i].c_str());
                if (irow==0)
                    cols->Set(Integer::NewFromUnsigned(i), name, ReadOnly);

                if ((*it)[i].is_null())
                {
                    row->Set(name, Undefined(), ReadOnly);
                    continue;
                }

                const string sql_type = (*it)[i].type().sql_name();

                const bool uns = sql_type.find("UNSIGNED")==string::npos;

                if (sql_type.find("BIGINT")!=string::npos)
                {
                    if (uns)
                    {
                        const uint64_t val = (uint64_t)(*it)[i];
                        if (val>UINT32_MAX)
                            row->Set(name, Number::New(val), ReadOnly);
                        else
                            row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
                    }
                    else
                    {
                        const int64_t val = (int64_t)(*it)[i];
                        if (val<INT32_MIN || val>INT32_MAX)
                            row->Set(name, Number::New(val), ReadOnly);
                        else
                            row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
                    }
                    continue;
                }

                // 32 bit
                if (sql_type.find("INT")!=string::npos)
                {
                    if (uns)
                        row->Set(name, Integer::NewFromUnsigned((uint32_t)(*it)[i]), ReadOnly);
                    else
                        row->Set(name, Integer::New((int32_t)(*it)[i]), ReadOnly);
                }

                if (sql_type.find("BOOL")!=string::npos )
                {
                    row->Set(name, Boolean::New((bool)(*it)[i]), ReadOnly);
                    continue;
                }

                if (sql_type.find("FLOAT")!=string::npos)
                {
                    ostringstream val;
                    val << setprecision(7) << (float)(*it)[i];
                    row->Set(name, Number::New(stod(val.str())), ReadOnly);
                    continue;

                }
                if (sql_type.find("DOUBLE")!=string::npos)
                {
                    row->Set(name, Number::New((double)(*it)[i]), ReadOnly);
                    continue;
                }

                if (sql_type.find("CHAR")!=string::npos ||
                    sql_type.find("TEXT")!=string::npos)
                {
                    row->Set(name, String::New((const char*)(*it)[i]), ReadOnly);
                    continue;
                }

                if (sql_type.find("TIMESTAMP")!=string::npos)
                {
                    row->Set(name, Date::New(time_t(mysqlpp::Time((*it)[i]))*1000), ReadOnly);
                    continue;
                }

                if (sql_type.find("DATETIME")!=string::npos)
                {
                    row->Set(name, Date::New(time_t(mysqlpp::DateTime((*it)[i]))*1000), ReadOnly);
                    continue;
                }

                if (sql_type.find(" DATE ")!=string::npos)
                {
                    row->Set(name, Date::New(time_t((mysqlpp::Date)(*it)[i])*1000), ReadOnly);
                    continue;
                }

            }

            ret->Set(Integer::NewFromUnsigned(irow++), row, ReadOnly);
        }

        if (irow>0)
            ret->Set(String::New("cols"), cols, ReadOnly);

        return handle_scope.Close(ret);
    }
    catch (const exception &e)
    {
        return ThrowException(String::New(e.what()));
    }
#endif
}

Handle<Value> InterpreterV8::FuncDatabase(const Arguments &args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    HandleScope handle_scope;

    const String::Utf8Value database(args[0]);
    const String::Utf8Value query   (args[1]);

#ifdef HAVE_SQL
    try
    {
        Database *db = new Database(*database);
        fDatabases.push_back(db);

        Handle<ObjectTemplate> tem = ObjectTemplate::New();
        tem->Set(String::New("user"),     String::New(db->user.c_str()), ReadOnly);
        tem->Set(String::New("server"),   String::New(db->server.c_str()), ReadOnly);
        tem->Set(String::New("database"), String::New(db->db.c_str()), ReadOnly);
        tem->Set(String::New("port"),     db->port==0?Undefined():Integer::NewFromUnsigned(db->port), ReadOnly);
        tem->Set(String::New("query"),    FunctionTemplate::New(WrapDbQuery), ReadOnly);
        tem->Set(String::New("close"),    FunctionTemplate::New(WrapDbClose),   ReadOnly);
        tem->SetInternalFieldCount(1);

        Handle<Object> obj = tem->NewInstance();
        obj->SetInternalField(0, External::New(db));

        return handle_scope.Close(obj);
    }
    catch (const exception &e)
    {
        return ThrowException(String::New(e.what()));
    }
#endif
}

Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
{
    // Dim values are always unsigned per (FACT++) definition
    switch (type)
    {
    case 'F':
        {
            // Remove the "imprecision" effect coming from casting a float to
            // a double and then showing it with double precision
            ostringstream val;
            val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
            Handle<Value> v=Number::New(stod(val.str()));
            ptr+=4;
            return v;
        }
    case 'D':  { Handle<Value> v=Number::New(*reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
    case 'I':
    case 'L':  { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
    case 'X':
        {
            const uint64_t val = *reinterpret_cast<const uint64_t*>(ptr);
            ptr += 8;
            if (val>UINT32_MAX)
                return Number::New(val);
            return Integer::NewFromUnsigned(val);
        }
    case 'S':  { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
    case 'C':  { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr));  ptr += 1; return v; }
    case ':':  { Handle<Value> v=String::New(ptr); return v; }
    }
    return Undefined();
}

Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
{
    HandleScope handle_scope;

    //const void *ptr = Local<External>::Cast(info.This()->GetInternalField(0))->Value();

    const String::Utf8Value str(args.Holder()->Get(String::New("name")));
    return Boolean::New(JsUnsubscribe(*str));
}

Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
{
    HandleScope handle_scope;

    const String::Utf8Value str(args.Holder()->Get(String::New("name")));

    const pair<uint64_t, EventImp *> p = JsGetEvent(*str);

    const EventImp *evt = p.second;
    if (!evt)
        return Undefined();

    //if (counter==cnt)
    //    return info.Holder();//Holder()->Get(String::New("data"));

    const vector<Description> vec = JsDescription(*str);

    Handle<Array> ret = Array::New();
    ret->Set(String::New("format"),  String::New(evt->GetFormat().c_str()), ReadOnly);
    ret->Set(String::New("named"),   Boolean::New(vec.size()>0), ReadOnly);
    ret->Set(String::New("counter"), Integer::New(p.first), ReadOnly);
    ret->Set(String::New("time"),    Date::New(evt->GetJavaDate()), ReadOnly);
    ret->Set(String::New("qos"),     Integer::New(evt->GetQoS()), ReadOnly);

    typedef boost::char_separator<char> separator;
    const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));

    const vector<string> tok(tokenizer.begin(), tokenizer.end());

    Handle<Array> obj = tok.size()==1 ? ret : Array::New();

    const char *ptr = evt->GetText();
    try
    {
        size_t pos = 1;
        for (auto it=tok.begin(); it!=tok.end(); it++, pos++)
        {
            char type = (*it)[0];
            it++;

            if (it==tok.end() && type=='C')
                type = ':';

            if (it==tok.end() && type!=':')
                return ThrowException(String::New(("Format string invalid '"+evt->GetFormat()+"'").c_str()));

            string name = pos<vec.size() ? vec[pos].name : "";
            if (tok.size()==1)
                name = "data";

            const uint32_t cnt = it==tok.end() ? 1 : stoi(it->c_str());

            if (cnt==1)
            {
                const Handle<Value> v = Convert(type, ptr);
                if (tok.size()>1)
                    obj->Set(pos-1, v);
                if (!name.empty())
                    obj->Set(String::New(name.c_str()), v);
            }
            else
            {
                Handle<Array> a = Array::New(cnt);
                for (uint32_t i=0; i<cnt; i++)
                    a->Set(i, Convert(type, ptr));
                if (tok.size()>1)
                    obj->Set(pos-1, a);
                if (!name.empty())
                    obj->Set(String::New(name.c_str()), a);
            }

            if (it==tok.end())
                break;
        }

        if (tok.size()>1)
            ret->Set(String::New("data"), obj, ReadOnly);

        return handle_scope.Close(ret);
    }
    catch (...)
    {
        return ThrowException(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
    }
}

/*
void Cleanup( Persistent<Value> object, void *parameter )
{
    cout << "======================> RemoveMyObj()" << endl;
}*/

Handle<Value> InterpreterV8::FuncOpen(const Arguments &args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    //if (!args.IsConstructCall())
    //    return ThrowException(String::New("Must be used as constructor."));

    HandleScope handle_scope;

    const String::Utf8Value str(args[0]);

    void *ptr = JsSubscribe(*str);
    if (ptr==0)
        return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));

    Handle<ObjectTemplate> tem = ObjectTemplate::New();
    tem->Set(String::New("get"),   FunctionTemplate::New(WrapGetData), ReadOnly);
    tem->Set(String::New("close"), FunctionTemplate::New(WrapClose),   ReadOnly);
    tem->Set(String::New("name"),  String::New(*str), ReadOnly);
    tem->SetInternalFieldCount(1);
    //tem->Set(String::New("toString"), String::New(("[object Dim "+string(*str)+"]").c_str()), ReadOnly);

    Handle<Object> obj = tem->NewInstance();
    obj->SetInternalField(0, External::New(ptr));

    return handle_scope.Close(obj);

    // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
    // obj.MakeWeak((void*)1, Cleanup);
    // return obj;
}

bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
{
    v8::Locker locker;
    fThreadId = V8::GetCurrentThreadId();

    JsLoad(filename);

    HandleScope handle_scope;

    // Create a template for the global object.
    Handle<ObjectTemplate> dim = ObjectTemplate::New();
    dim->Set(String::New("print"),    FunctionTemplate::New(WrapPrint),    ReadOnly);
    dim->Set(String::New("out"),      FunctionTemplate::New(WrapOut),      ReadOnly);
    dim->Set(String::New("wait"),     FunctionTemplate::New(WrapWait),     ReadOnly);
    dim->Set(String::New("send"),     FunctionTemplate::New(WrapSend),     ReadOnly);
    dim->Set(String::New("state"),    FunctionTemplate::New(WrapState),    ReadOnly);
    dim->Set(String::New("sleep"),    FunctionTemplate::New(WrapSleep),    ReadOnly);
    dim->Set(String::New("open"),     FunctionTemplate::New(WrapOpen),     ReadOnly);
    dim->Set(String::New("database"), FunctionTemplate::New(WrapDatabase), ReadOnly);

    Handle<ObjectTemplate> global = ObjectTemplate::New();
    global->Set(String::New("dim"), dim, ReadOnly);
    global->Set(String::New("include"), FunctionTemplate::New(WrapInclude),                ReadOnly);
    global->Set(String::New("exit"),    FunctionTemplate::New(WrapExit),                   ReadOnly);
    global->Set(String::New("version"), FunctionTemplate::New(InterpreterV8::FuncVersion), ReadOnly);

    // Persistent
    Persistent<Context> context = Context::New(NULL, global);
    if (context.IsEmpty())
    {
        //printf("Error creating context\n");
        return false;
    }

    v8::Context::Scope scope(context);

    Local<Array> args = Array::New(map.size());
    for (auto it=map.begin(); it!=map.end(); it++)
        args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
    context->Global()->Set(String::New("$"),   args, ReadOnly);
    context->Global()->Set(String::New("arg"), args, ReadOnly);

    JsStart(filename);

    //context->Enter();
    v8::Locker::StartPreemption(10);
    const bool rc = ExecuteFile(filename);

    // -----
    // This is how an exit handler could look like, but there is no way to interrupt it
    // -----
    // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
    // if (!obj.IsEmpty())
    // {
    //     Handle<Value> onexit = obj->Get(String::New("onexit"));
    //     if (!onexit->IsUndefined())
    //         Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
    //     // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
    // }

    v8::Locker::StopPreemption();
    //context->Exit();

    context.Dispose();

#ifdef HAVE_SQL
    for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
        delete *it;
    fDatabases.clear();
#endif


    JsEnd(filename);

    return rc;
}

void InterpreterV8::JsStop()
{
    Locker locker;
    //cout << "Terminate " << fThreadId << endl;
    if (This->fThreadId>=0)
        V8::TerminateExecution(This->fThreadId);
    //cout << "Terminate " << fThreadId << endl;
    Unlocker unlocker;
}

#endif

