local createVersion = require('/apis/libversion');

local command = ...;

local function printUsage()
  print('events usage:');
  print();
  print('\t\t\tevents');
  print('\t\t\tevents version');
  print('\t\t\tevents help');
end

local function sanitize(value, seen)
  local valueType = type(value);

  if valueType == 'function' then
    return '<function>';
  end

  if valueType ~= 'table' then
    return value;
  end

  seen = seen or {};
  if seen[value] then
    return '<cycle>';
  end

  seen[value] = true;

  local result = {};
  for k, v in pairs(value) do
    result[sanitize(k, seen)] = sanitize(v, seen);
  end

  seen[value] = nil;
  return result;
end

local function valueToString(value)
  if type(value) == 'string' then
    return value;
  end

  local ok, serialized = pcall(textutils.serialize, sanitize(value), { compact = true });
  if ok then
    return serialized;
  end

  return '<' .. type(value) .. '>';
end

if command == 'version' or command == '-version' or command == '--version' then
  print('v' .. createVersion().forSelf());
  return;
end

if command == 'help' or command == '-help' or command == '--help' then
  printUsage();
  return;
end

if command ~= nil and command ~= '' then
  printUsage();
  return;
end

print('Listening events... Press Ctrl+T to stop.');

while true do
  local event = table.pack(os.pullEventRaw());

  if event[1] == 'terminate' then
    return;
  end

  local parts = {};

  for i = 1, event.n do
    parts[i] = valueToString(event[i]);
  end

  print(table.concat(parts, ' '));
end
