var _hooks = {};

function rsapi(event, id, data) {
  console.log(`rsapi:${id}:${JSON.stringify(data)}`);
  if (_hooks[id]) _hooks[id](event, data);
}

const RSEvent = {
  on: (id, func) => {
    _hooks[id] = func;
  },
};

function getData(event) {
  return {
    username: event.player ? String(event.player.username) : null,
    message: event.message ? String(event.message) : null,
    input: event.input ? String(event.input) : null,
  };
}

///////////////////
/// === API === ///
///////////////////

// rsapi:event.playerJoined:"Player"
PlayerEvents.loggedIn((event) => {
  const { username } = getData(event);
  rsapi(event, "event.playerJoined", username);
});

// rsapi:event.playerLeft:"Player"
PlayerEvents.loggedOut((event) => {
  const { username } = getData(event);
  rsapi(event, "event.playerLeft", username);
});

// rsapi:event.playerChat:["Player","Message"]
PlayerEvents.chat((event) => {
  const { username, message } = getData(event);
  rsapi(event, "event.playerChat", [username, message]);
});

// rsapi:event.serverChat:"Message"
ServerEvents.command("say", (event) => {
  const { input } = getData(event);
  rsapi(
    event,
    "event.serverChat",
    input.startsWith("say ") ? input.slice(4) : input,
  );
});

// rsapi:event.playerDied:"Player"
EntityEvents.death("player", (event) => {
  const { username } = getData(event);
  rsapi(event, "event.playerDied", username);
});

/////////////////////
/// === HOOKS === ///
/////////////////////

RSEvent.on("event.playerJoined", (event, username) => {
  function title(player, message) {
    event.server.runCommandSilent("title @a times 20 200 20");
    event.server.runCommandSilent(
      "title " + player + ' title ["' + message + '"]',
    );
  }

  if (username === "Sbebas_s") title(username, "MCFLURRY!!!!");
  else if (username === "Mark917") title(username, "CUCARACHA");
  else if (username === "Anthony_7") title(username, "onion rings");
  else if (username === "Tren_boy") title(username, "Kebab");
  else if (username === "Cheruz") title(username, "Basta\ngiocare\nnegro");
  else title(username, "Welcome");
});
