/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

ChromeUtils.import("resource://gre/modules/TelemetryLog.jsm", this);
ChromeUtils.import("resource://gre/modules/TelemetrySession.jsm", this);

const TEST_PREFIX = "TEST-";
const TEST_REGEX = new RegExp("^" + TEST_PREFIX);

const LOG_ENTRY_MAX_COUNT = 1000;

function check_event(event, id, data) {
  info("Checking message " + id);
  Assert.equal(event[0], id);
  Assert.ok(event[1] > 0);

  if (data === undefined) {
    Assert.ok(event.length == 2);
  } else {
    Assert.equal(event.length, data.length + 2);
    for (var i = 0; i < data.length; ++i) {
      Assert.equal(typeof(event[i + 2]), "string");
      Assert.equal(event[i + 2], data[i]);
    }
  }
}

add_task(async function() {
  do_get_profile();
  await TelemetryController.testSetup();

  TelemetryLog.log(TEST_PREFIX + "1", ["val", 123, undefined]);
  TelemetryLog.log(TEST_PREFIX + "2", []);
  TelemetryLog.log(TEST_PREFIX + "3");

  var log = TelemetryLog.entries().filter(function(e) {
    // Only want events that were generated by the test.
    return TEST_REGEX.test(e[0]);
  });

  Assert.equal(log.length, 3);
  check_event(log[0], TEST_PREFIX + "1", ["val", "123", "undefined"]);
  check_event(log[1], TEST_PREFIX + "2", []);
  check_event(log[2], TEST_PREFIX + "3", undefined);
  Assert.ok(log[0][1] <= log[1][1]);
  Assert.ok(log[1][1] <= log[2][1]);

  // Test that we limit the overall length of the log, and that pushing
  // it over the limit keeps the older events.
  for (let i = 0; i < LOG_ENTRY_MAX_COUNT + 1; i++) {
    TelemetryLog.log(TEST_PREFIX + "to_tha_limit");
  }
  log = TelemetryLog.entries();
  Assert.equal(log.length, LOG_ENTRY_MAX_COUNT);
  check_event(log[0], TEST_PREFIX + "1", ["val", "123", "undefined"]);

  await TelemetryController.testShutdown();
});
