#include "AFBClient.h"

#include <cctype>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#define UNUSED(x) (void)(x)

namespace {

constexpr const int token_maxlen = 20;
constexpr const char *const wmAPI = "winman";

struct ScopeTrace {
   static int indent;
   char const *f{};
   ScopeTrace(char const *func) : f(func) {
      fprintf(stderr, "%*s%s -->\n", 2 * indent++, "", this->f);
   }
   ~ScopeTrace() {
      fprintf(stderr, "%*s%s <--\n", 2 * --indent, "", this->f);
   }
};
int ScopeTrace::indent = 0;

#ifndef NDEBUG
#define TRACE()
#else
#define TRACE() ScopeTrace __attribute__((unused)) trace_scope_here__(__PRETTY_FUNCTION__)
#endif

/* called when wsj1 receives a method invocation */
void onCall(void *closure, const char *api, const char *verb, struct afb_wsj1_msg *msg)
{
   TRACE();
    UNUSED(closure);
    int rc;
    printf("ON-CALL %s/%s:\n%s\n", api, verb,
           json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
                                          JSON_C_TO_STRING_PRETTY));
    fflush(stdout);
    rc = afb_wsj1_reply_error_s(msg, "\"unimplemented\"", nullptr);
    if (rc < 0)
        fprintf(stderr, "replying failed: %m\n");
}

/* called when wsj1 receives an event */
void onEvent(void *closure, const char *event, afb_wsj1_msg *msg)
{
   TRACE();
    UNUSED(closure);
    printf("ON-EVENT %s:\n%s\n", event,
           json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
                                          JSON_C_TO_STRING_PRETTY));
    fflush(stdout);
}

/* called when wsj1 hangsup */
void onHangup(void *closure, afb_wsj1 *wsj1)
{
   TRACE();
    UNUSED(closure);
    UNUSED(wsj1);
    printf("ON-HANGUP\n");
    fflush(stdout);
    exit(0);
}

/* called when wsj1 receives a reply */
void onReply(void *closure, afb_wsj1_msg *msg)
{
   TRACE();
    printf("ON-REPLY %s: %s\n%s\n", (char*)closure,
           afb_wsj1_msg_is_reply_ok(msg) ? "OK" : "ERROR",
           json_object_to_json_string_ext(afb_wsj1_msg_object_j(msg),
                                          JSON_C_TO_STRING_PRETTY));
    fflush(stdout);
    free(closure);
}

}  // namespace

AFBClient &AFBClient::instance()
{
   TRACE();
   static AFBClient obj;
   return obj;
}

AFBClient::AFBClient() : wsj1{}, itf{}, loop{}
{
   TRACE();
    ///* itinializing the callback interface for wsj1 */
    itf.on_hangup = onHangup;
    itf.on_call = onCall;
    itf.on_event = onEvent;
}

AFBClient::~AFBClient()
{
   TRACE();
   sd_event_unref(loop);
   loop = nullptr;
}

int AFBClient::init(int port, char const *token)
{
   TRACE();
    char *uribuf = nullptr;
    int rc = -1;

    if (!token || strlen(token) > token_maxlen) {
       fprintf(stderr, "Token is invalid\n");
       rc = -EINVAL;
       goto fail;
    }

    for (char const *p = token; *p; p++) {
       if (!isalnum(*p)) {
          fprintf(stderr, "Token is invalid\n");
          rc = -EINVAL;
          goto fail;
       }
    }

    if (port < 1 && port > 0xffff) {
       fprintf(stderr, "Port is invalid\n");
       rc = -EINVAL;
       goto fail;
    }

    /* get the default event loop */
    rc = sd_event_default(&loop);
    if (rc < 0) {
        fprintf(stderr, "Connection to default event loop failed: %s\n", strerror(-rc));
        goto fail;
    }

    asprintf(&uribuf, "ws://localhost:%d/api?token=%s", port, token);

    /* connect the websocket wsj1 to the uri given by the first argument */
    wsj1 = afb_ws_client_connect_wsj1(loop, uribuf, &itf, nullptr);
    if (wsj1 == nullptr) {
        sd_event_unref(loop);
        fprintf(stderr, "Connection to %s failed: %m\n", uribuf);
        rc = -errno;
        goto fail;
    }

    return 0;

fail:
    return rc;
}

int AFBClient::dispatch(uint64_t timeout) {
   TRACE();
    return sd_event_run(loop, timeout);
}

int AFBClient::requestSurface(const char *label)
{
   TRACE();
   constexpr char const *verb = "request_surface";

   json_object *jp = json_object_new_object();
   json_object_object_add(jp, "drawing_name", json_object_new_string(label));

   // std::experimental::optional look-alike
   struct optional {
      int value;
      bool is_not_set;
   };

   constexpr struct optional const nullopt = {0, true};
   auto id = nullopt;

   /* send the request */
   int rc = afb_wsj1_call_j(
      wsj1, wmAPI, verb, jp,
      [](void *closure, afb_wsj1_msg *msg) {
         if (afb_wsj1_msg_is_reply_ok(msg)) {
            int id = json_object_get_int(
               json_object_object_get(afb_wsj1_msg_object_j(msg), "response"));
            auto oid = (optional *)closure;
            *oid = optional{id};
         } else
            fprintf(stderr, "wrong request surface reply received!\n");
      },
      (void *)&id);

   if (rc < 0) {
      fprintf(stderr, "calling %s/%s(%s) failed: %m\n", wmAPI, verb,
              json_object_to_json_string(jp));
   } else {
      // Lets make this call sync here...
      dispatch(-1);

      if (! id.is_not_set) {
          char *buf;
          asprintf(&buf, "%d", id.value);
          printf("setenv(\"QT_IVI_SURFACE_ID\", %s, 1)\n", buf);
          if (setenv("QT_IVI_SURFACE_ID", buf, 1) != 0) {
              fprintf(stderr, "putenv failed: %m\n");
          } else {
              rc = 0; // Single point of success
          }
      } else {
          fprintf(stderr, "Could not get surface ID from WM\n");
          rc = -EINVAL;
      }
   }

   return rc;
}

int AFBClient::activateSurface(const char *label)
{
   TRACE();

    const char begin[] = "{\"drawing_name\":\"";
    const char end[] = "\"}";
    const char verb[] = "activate_surface";
    char *parameter = (char *)malloc(strlen(begin) +
                                     strlen(label) +
                                     strlen(end) + 1);
    strcpy(parameter, begin);
    strcat(parameter, label);
    strcat(parameter, end);
    call(wmAPI, verb, parameter);

    // Sync this one too
    dispatch(-1);

    return 0;
}

int AFBClient::deactivateSurface(const char *label)
{
   TRACE();
    json_object *j = json_object_new_object();
    json_object_object_add(j, "drawing_name", json_object_new_string(label));
    call(wmAPI, "deactivate_surface", json_object_to_json_string(j));
    json_object_put(j);
    dispatch(-1);
    return 0;
}

int AFBClient::endDraw(const char *label)
{
   TRACE();
    json_object *j = json_object_new_object();
    json_object_object_add(j, "drawing_name", json_object_new_string(label));
    call(wmAPI, "enddraw", json_object_to_json_string(j));
    json_object_put(j);
    dispatch(-1);
    return 0;
}

/* makes a call */
void AFBClient::call(const char *api, const char *verb, const char *object)
{
   TRACE();
    static int num = 0;
    char *key;
    int rc;

    fflush(stdout);

    /* allocates an id for the request */
    rc = asprintf(&key, "%d:%s/%s", ++num, api, verb);

    /* send the request */
    rc = afb_wsj1_call_s(wsj1, api, verb, object, onReply, key);
    if (rc < 0)
        fprintf(stderr, "calling %s/%s(%s) failed: %m\n", api, verb, object);

    fflush(stdout);
}

void AFBClient::set_event_handler(enum EventType at, std::function<void(char const *)> func) {
   TRACE();
   // XXX todo
}