#include "pl_util.h"
#include "pl_inlined.h"

static struct {
    const char* file_name;
    const char* source;
} js_inlined[] = {
    {
        "c_eventloop.js", /* on my mac, this eval takes 574.697134 us avg */

        "/*\n"
        " *  C eventloop example (c_eventloop.c).\n"
        " *\n"
        " *  Ecmascript code to initialize the exposed API (setTimeout() etc) when\n"
        " *  using the C eventloop.\n"
        " *\n"
        " *  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Timers\n"
        " */\n"
        "\n"
        "/*\n"
        " *  Timer API\n"
        " */\n"
        "\n"
        "function setTimeout(func, delay) {\n"
        "    var cb_func;\n"
        "    var bind_args;\n"
        "    var timer_id;\n"
        "\n"
        "    // Delay can be optional at least in some contexts, so tolerate that.\n"
        "    // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\n"
        "    if (typeof delay !== 'number') {\n"
        "        if (typeof delay === 'undefined') {\n"
        "            delay = 0;\n"
        "        } else {\n"
        "            throw new TypeError('invalid delay');\n"
        "        }\n"
        "    }\n"
        "\n"
        "    if (typeof func === 'string') {\n"
        "        // Legacy case: callback is a string.\n"
        "        cb_func = eval.bind(this, func);\n"
        "    } else if (typeof func !== 'function') {\n"
        "        throw new TypeError('callback is not a function/string');\n"
        "    } else if (arguments.length > 2) {\n"
        "        // Special case: callback arguments are provided.\n"
        "        bind_args = Array.prototype.slice.call(arguments, 2);  // [ arg1, arg2, ... ]\n"
        "        bind_args.unshift(this);  // [ global(this), arg1, arg2, ... ]\n"
        "        cb_func = func.bind.apply(func, bind_args);\n"
        "    } else {\n"
        "        // Normal case: callback given as a function without arguments.\n"
        "        cb_func = func;\n"
        "    }\n"
        "\n"
        "    timer_id = EventLoop.createTimer(cb_func, delay, true /*oneshot*/);\n"
        "\n"
        "    return timer_id;\n"
        "}\n"
        "\n"
        "function clearTimeout(timer_id) {\n"
        "    if (typeof timer_id !== 'number') {\n"
        "        throw new TypeError('timer ID is not a number');\n"
        "    }\n"
        "    var success = EventLoop.deleteTimer(timer_id);  /* retval ignored */\n"
        "}\n"
        "\n"
        "function setInterval(func, delay) {\n"
        "    var cb_func;\n"
        "    var bind_args;\n"
        "    var timer_id;\n"
        "\n"
        "    if (typeof delay !== 'number') {\n"
        "        if (typeof delay === 'undefined') {\n"
        "            delay = 0;\n"
        "        } else {\n"
        "            throw new TypeError('invalid delay');\n"
        "        }\n"
        "    }\n"
        "\n"
        "    if (typeof func === 'string') {\n"
        "        // Legacy case: callback is a string.\n"
        "        cb_func = eval.bind(this, func);\n"
        "    } else if (typeof func !== 'function') {\n"
        "        throw new TypeError('callback is not a function/string');\n"
        "    } else if (arguments.length > 2) {\n"
        "        // Special case: callback arguments are provided.\n"
        "        bind_args = Array.prototype.slice.call(arguments, 2);  // [ arg1, arg2, ... ]\n"
        "        bind_args.unshift(this);  // [ global(this), arg1, arg2, ... ]\n"
        "        cb_func = func.bind.apply(func, bind_args);\n"
        "    } else {\n"
        "        // Normal case: callback given as a function without arguments.\n"
        "        cb_func = func;\n"
        "    }\n"
        "\n"
        "    timer_id = EventLoop.createTimer(cb_func, delay, false /*oneshot*/);\n"
        "\n"
        "    return timer_id;\n"
        "}\n"
        "\n"
        "function clearInterval(timer_id) {\n"
        "    if (typeof timer_id !== 'number') {\n"
        "        throw new TypeError('timer ID is not a number');\n"
        "    }\n"
        "    EventLoop.deleteTimer(timer_id);\n"
        "}\n"
        "\n"
        "function requestEventLoopExit() {\n"
        "    EventLoop.requestExit();\n"
        "}\n"
        "\n"
        "/*\n"
        " *  Socket handling\n"
        " *\n"
        " *  Ideally this would be implemented more in C than here for more speed\n"
        " *  and smaller footprint: C code would directly maintain the callback state\n"
        " *  and such.\n"
        " *\n"
        " *  Also for more optimal I/O, the buffer churn caused by allocating and\n"
        " *  freeing a lot of buffer values could be eliminated by reusing buffers.\n"
        " *  Socket reads would then go into a pre-allocated buffer, for instance.\n"
        " */\n"
        "\n"
        "EventLoop.socketListening = {};\n"
        "EventLoop.socketReading = {};\n"
        "EventLoop.socketConnecting = {};\n"
        "\n"
        "EventLoop.fdPollHandler = function(fd, revents) {\n"
        "    var data;\n"
        "    var cb;\n"
        "    var rc;\n"
        "    var acc_res;\n"
        "\n"
        "    //print('activity on fd', fd, 'revents', revents);\n"
        "\n"
        "    if (revents & Poll.POLLIN) {\n"
        "        cb = this.socketReading[fd];\n"
        "        if (cb) {\n"
        "            data = Socket.read(fd);  // no size control now\n"
        "            //print('READ', Duktape.enc('jx', data));\n"
        "            if (data.length === 0) {\n"
        "                this.close(fd);\n"
        "                return;\n"
        "            }\n"
        "            cb(fd, data);\n"
        "        } else {\n"
        "            cb = this.socketListening[fd];\n"
        "            if (cb) {\n"
        "                acc_res = Socket.accept(fd);\n"
        "                //print('ACCEPT:', Duktape.enc('jx', acc_res));\n"
        "                cb(acc_res.fd, acc_res.addr, acc_res.port);\n"
        "            } else {\n"
        "                //print('UNKNOWN');\n"
        "            }\n"
        "        }\n"
        "    }\n"
        "\n"
        "    if (revents & Poll.POLLOUT) {\n"
        "        // Connected\n"
        "        cb = this.socketConnecting[fd];\n"
        "        if (cb) {\n"
        "            delete this.socketConnecting[fd];\n"
        "            cb(fd);\n"
        "        }\n"
        "    }\n"
        "\n"
        "    if ((revents & ~(Poll.POLLIN | Poll.POLLOUT)) !== 0) {\n"
        "        //print('unexpected revents, close fd');\n"
        "        this.close(fd);\n"
        "    }\n"
        "}\n"
        "\n"
        "EventLoop.server = function(address, port, cb_accepted) {\n"
        "    var fd = Socket.createServerSocket(address, port);\n"
        "    this.socketListening[fd] = cb_accepted;\n"
        "    this.listenFd(fd, Poll.POLLIN);\n"
        "}\n"
        "\n"
        "EventLoop.connect = function(address, port, cb_connected) {\n"
        "    var fd = Socket.connect(address, port);\n"
        "    this.socketConnecting[fd] = cb_connected;\n"
        "    this.listenFd(fd, Poll.POLLOUT);\n"
        "}\n"
        "\n"
        "EventLoop.close = function(fd) {\n"
        "    EventLoop.listenFd(fd, 0);\n"
        "    delete this.socketListening[fd];\n"
        "    delete this.socketReading[fd];\n"
        "    delete this.socketConnecting[fd];\n"
        "    Socket.close(fd);\n"
        "}\n"
        "\n"
        "EventLoop.setReader = function(fd, cb_read) {\n"
        "    this.socketReading[fd] = cb_read;\n"
        "    this.listenFd(fd, Poll.POLLIN);\n"
        "}\n"
        "\n"
        "EventLoop.write = function(fd, data) {\n"
        "    // This simple example doesn't have support for write blocking / draining\n"
        "    var rc = Socket.write(fd, Duktape.Buffer(data));\n"
        "}\n"
    },
};

void pl_register_inlined_functions(Duk* duk)
{
    dTHX;
    for (size_t j = 0; j < sizeof(js_inlined) / sizeof(js_inlined[0]); ++j) {
        pl_eval(aTHX_ duk, js_inlined[j].source, js_inlined[j].file_name);
    }
}
