"use strict";

console.log("Pong script was run!");

const connection = new signalR.HubConnectionBuilder()
  .withUrl("/pong/hub")
  .withAutomaticReconnect()
  .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())
  .build();

function getElement(id) {
  return document.getElementById(id) ?? console.error(`Element #${id} not found!`)
}

const connectionStatus = getElement("connection");
const createlobby = getElement("createlobby");
const roomid = getElement("roomid");
const joinroom = getElement("joinroom");
const usernameinput = getElement("username");
const setusername = getElement("setusername");
const leavelobby = getElement("leavelobby");

connection.onclose(function (error) {
  if (error) {
    connectionStatus.textContent = "Unexpected error!";
    return console.error(`Connection aborted: ${error.message}`);
  }
  console.info("Disconnected!");
  connectionStatus.textContent = "Closed!";
});

connection.onreconnecting(function (error) {
  if (error) {
    connectionStatus.textContent = "Reconnecting!";
    return console.error(`Connection reconnecting: ${error.message}`);
  }
  console.info("Reconnecting!");
  connectionStatus.textContent = "Reconnecting!";
});

connection.onreconnected(function (connectionId) {
  console.info(`Connected as ${connectionId}!`);
  connectionStatus.textContent = "Connected!";
});

createlobby.addEventListener("click", function (event) {
  connection.invoke("CreateRoom").catch(function (err) {
    return console.error(err.toString());
  });
  event.preventDefault();
});

connection.on("GameStateChanged", function (state) {
  console.info(`Game is now in state ${state}`);
});
connection.on("UsernameChanged", function (username) {
  console.info(`Username is now ${username}`);
  usernameinput.value = username;
});

joinroom.addEventListener("click", function (event) {
  connection.invoke("JoinRoom", roomid.value).catch(function (err) {
    return console.error(err.toString());
  });
  event.preventDefault();
});

setusername.addEventListener("click", function (event) {
  connection.invoke("RequestUsernameChange", usernameinput.value).catch(function (err) {
    return console.error(err.toString());
  });
  event.preventDefault();
});

leavelobby.addEventListener("click", function (event) {
  connection.invoke("LeaveRoom").catch(function (err) {
    return console.error(err.toString());
  });
  event.preventDefault();
});

connection.start().then(function () {
  console.info(`Connected!`);
  connectionStatus.textContent = "Connected!";
}).catch(function (err) {
  connectionStatus.textContent = "Connection failed!";
  return console.error(err.toString());
});