summaryrefslogtreecommitdiff
path: root/src/main/resources/static/app.js
blob: dfdcf9345b84ec67a7945a8b52d028404036fcd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var stompClient = null;

function setConnected(connected) {
  $("#connect").prop("disabled", connected);
  $("#disconnect").prop("disabled", !connected);
  if (connected) {
    $("#game-list").show();
  } else {
    $("#game-list").hide();
  }
  $("#greetings").html("");
}

function connect() {
  var socket = new SockJS('/seven-wonders-websocket');
  stompClient = Stomp.over(socket);
  stompClient.connect({}, function (frame) {
    setConnected(true);
    console.log('Connected: ' + frame);

    stompClient.subscribe('/topic/games', function (gameId) {
      console.log("Received new game: " + gameId);
      addNewGame(gameId.body);
    });

    stompClient.subscribe('/topic/players', function (player) {
      console.log("Received new player: " + player);
      addNewPlayer(JSON.parse(player.body));
    });
  });
}

function disconnect() {
  if (stompClient != null) {
    stompClient.disconnect();
  }
  setConnected(false);
  console.log("Disconnected");
}

function sendCreateGame() {
  stompClient.send("/app/lobby/create-game", {}, "");
}

function sendJoinGame(gameId) {
  stompClient.send("/app/lobby/join-game", {},
          JSON.stringify({'gameId': gameId, 'playerName': $("#player-name-field").val()}));
}

function addNewGame(gameId) {
  console.log(gameId);
  $("#game-list-content").append('<tr><td>' + gameId + '</td><td><button id="join-' + gameId + '" type="submit">Join</button></td></tr>');
  $("#join-" + gameId).click(function () {
    sendJoinGame(gameId);
  });
}

function addNewPlayer(player) {
  console.log(player);
}

$(function () {
  $("form").on('submit', function (e) {
    e.preventDefault();
  });
  $("#connect").click(function () {
    connect();
  });
  $("#disconnect").click(function () {
    disconnect();
  });
  $("#create-game").click(function () {
    sendCreateGame();
  });
  $("#join-game").click(function () {
    sendJoinGame();
  });
});
bgstack15