#include "rktwebview.h"
#include <string>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "utils.h"

void evt_cb(int n)
{
    fprintf(stderr, "events waiting: %d - %d\n", n, rkt_webview_events_waiting());
}

int main(int argc, char *argv[])
{
    std::string me = argv[0];

    std::string loc = basedir(me);
#ifdef _WIN32
    std::string prg = loc + "\\rktwebview_prg.exe";
    SetDllDirectoryA("C:\\Qt\\6.11.1\\msvc2022_64\\bin");
#else
    std::string prg = loc + "/rktwebview_prg";
#endif

#ifdef _WIN32
    {
        std::string e = std::string("RKT_WEBVIEW_PRG=") + prg;
        _putenv(e.c_str());
    }
#else
    setenv("RKT_WEBVIEW_PRG", prg.c_str(), true);
    setenv("LD_LIBRARY_PATH", loc.c_str(), true);
#endif

    rkt_webview_init(__FUNCTION__);

    int context = rkt_webview_new_context("", nullptr);
    rkt_webview_set_loglevel(rkt_webview_loglevel_t::log_debug);

    const char *icon_file = "../../resource/rktplayer.png";
    FILE *f = fopen(icon_file, "rb");
    if (f == nullptr) {
        WARN1("Cannot find icon file %s\n", icon_file);
    } else {
        fclose(f);
    }
    int tray_wv = rkt_webview_tray_create(icon_file, "This is a test tray icon");
    INFO1("tray_wv = %d\n", tray_wv);

    rkt_webview_register_evt_callback(evt_cb);

    int wv = rkt_webview_create(context, 0);
    rkt_webview_set_title(wv, "Hi there, this is a title!");
    rkt_webview_set_icon(wv, "../../rktplayer.png");

    rkt_data_t *d = rkt_webview_info();
    rkt_webview_free_data(d);

    rkt_webview_move(wv, 100, 200);
    rkt_webview_resize(wv, 800, 600);
    //rkt_webview_set_url(wv, "https://wikipedia.org");
    rkt_webview_set_html(wv, "<html><head><title>Hi!</title></head><body><h1>Oke test</h1><select id=\"sel-lang\"><option value=\"nl\" selected>Nederlands</option><option value=\"en\">English</option></select><p>Ja</p></body></html>");

    d = rkt_webview_info();
    fprintf(stderr, "%s\n", d->data.metrics.log_file);
    rkt_webview_free_data(d);

    while(rkt_webview_events_waiting() > 0) {
        rkt_data_t *d = rkt_webview_get_event();
        rkt_webview_free_data(d);
    }
#ifdef _WIN32
    Sleep(15000);
    rkt_webview_tray_show_message(tray_wv, "This is a title", "This is a message to display<br><b>Hopefully</b> it does display.");
    Sleep(15000);
#else
    sleep(30
          );
#endif
    d = rkt_webview_info();
    rkt_webview_free_data(d);

    rkt_webview_close(wv);

    d = rkt_webview_info();
    rkt_webview_free_data(d);

    rkt_webview_close(tray_wv);

    rkt_webview_cleanup();
}
