/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include <glib.h>
#include "bulfius.h"
#include "utils.h"


#define REPORTS_ENDPOINT "https://stats.biniou.net/red/stats"
#define REPORTS_VERSION  1


static void
bulfius_post(const char *endpoint, json_t *body)
{
  if (NULL != getenv("LEBINIOU_TEST")) {
    return;
  }

  struct _u_request req;

  ulfius_init_request(&req);
  req.http_verb = o_strdup("POST");
#if ULFIUS_VERSION_NUMBER >= 0x020702
  ulfius_set_request_properties(&req, U_OPT_HTTP_URL, REPORTS_ENDPOINT, U_OPT_HTTP_URL_APPEND, endpoint, U_OPT_TIMEOUT, 2000, U_OPT_NONE);
#else
  gchar *url = g_strdup_printf("%s%s", REPORTS_ENDPOINT, endpoint);
#if ULFIUS_VERSION_NUMBER >= 0x020607
  ulfius_set_request_properties(&req, U_OPT_HTTP_URL, url, U_OPT_TIMEOUT, 2000, U_OPT_NONE);
#else
  req.http_url = o_strdup(url);
  req.timeout = 2000;
#endif
  g_free(url);
#endif
  ulfius_set_json_body_request(&req, body);

  int res = ulfius_send_http_request(&req, NULL);
  if (res != U_OK) {
    xdebug("Error in http request: %d\n", res);
  }
  ulfius_clean_request(&req);
}


void
bulfius_post_report(const char *endpoint, json_t *fields, json_t *tags)
{
  if (NULL == json_object_get(fields, "time")) {
    json_object_set_new(fields, "time", json_integer(unix_timestamp() * 1e9));
  }
  uint8_t decref_fields = 0, decref_tags = 0;
  if (NULL == fields) {
    fields = json_object();
    decref_fields = 1;
  }
  if (NULL == tags) {
    tags = json_object();
    decref_tags = 1;
  }
  json_t *body = json_pack("{sisOsO}",
                           "version", REPORTS_VERSION,
                           "fields", fields,
                           "tags", tags);

  // DEBUG_JSON("body", body, 1);
  bulfius_post(endpoint, body);
  json_decref(body);
  if (decref_fields) {
    json_decref(fields);
  }
  if (decref_tags) {
    json_decref(tags);
  }
}
