var connectionsNum = 0;
var connections = [];

$(GLOBAL).bind("loadSettingsFromServerDone", function () {
  consoleLog("connect.js::loadSettingsFromServerDone event captured");
  getConnectedUsers();
});

$(GLOBAL).bind("assemble", function () {
  consoleLog("assemble event captured");
  $(".assembleButton").html("<img src='img/smallLoader.gif'/>");
});

$(GLOBAL).bind("assembleDone", function () {
  consoleLog("assembleDone event captured");
  $(".assembleButton").html($("#i18AssembleLabel").html());
});

$(GLOBAL).bind("appStart", function () {
  if (getUrlVars()["qr"] != null) {
    if (localStorage["uniqueId"] != null) {
      connectUser();
    } else {
      generateUniqueId(connectUser);
    }
  }
  if (localStorage["uniqueId"] != null) {
    getConnectedUsers();
  }
});

function connectUser(id, nickname) {
  if(typeof(id) == "undefined") {
    id = getUrlVars()["qr"];
  }
  consoleLog("connectUser: " + id);
  $(GLOBAL).trigger("connectUser");
  ajaxCall("/api/v1/connectUser.php", {
    uuid: localStorage["uniqueId"],
    qr: id
  }).fail(function (data) {
    consoleLog("connectUser error: " + data);
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          consoleLog("connectUser: " + data.response.message + " " + data.response.value);
          connectionsNum += 1;
          connections.push({ id: id, nickname: nickname });

          if (getUrlVars()["qr"] != null) {
            revealMessageDialog($("#i18ConnectSuccessLabel").html(), $("#i18ConnectSuccessDescription").html());
          }
          break;
        default:
          revealMessageDialog($("#i18ConnectErrorLabel").html(), data.response.responseCode + ": " + $("#i18ConnectErrorDescription").html());
          break;
      }
    } else {
      revealMessageDialog($("#i18ConnectErrorLabel").html(), data);
    }
  }).always(function () {
    consoleLog("connectUserDone fired");
    $(GLOBAL).trigger("connectUserDone");
  });
}

function disconnectUser(id) {
  consoleLog("disconnectUser: " + id);
  $(GLOBAL).trigger("disconnectUser");
  ajaxCall("/api/v1/disconnectUser.php", {
    uuid: localStorage["uniqueId"],
    qr: id
  }).fail(function (data) {
    consoleLog("disconnectUser error: " + data);
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          connectionsNum -= 1;
          // Remove connection from connections object array.
          for (key in connections) {
            if (connections[key]["id"] == id) {
              connections.splice(key);
              break;
            }
          }
          consoleLog("disconnectUser: " + data.response.message + " " + data.response.value);
          break;
        default:
          revealMessageDialog($("#i18DisconnectErrorLabel").html(), data.response.responseCode + ": " + $("#i18DisconnectErrorDescription").html());
          break;
      }
    } else {
      revealMessageDialog($("#i18DisconnectErrorLabel").html(), data);
    }
  }).always(function () {
    consoleLog("disconnectUserDone fired");
    $(GLOBAL).trigger("disconnectUserDone");
  });
}

function getConnectedUsers() {
  consoleLog("getConnectedUsers");
  $(GLOBAL).trigger("getConnectedUsers");

  $("#connectedPlayersPanelContent").html("<img src='img/smallLoader.gif'/>");
  connections = [];

  ajaxCall("/api/v1/getConnections.php", {
    uuid: localStorage["uniqueId"]
  }).fail(function (data) {
    consoleLog("getConnections error: " + data);
  }).done(function (data) {
    if (data.response != null) {
      switch (data.response.responseCode) {
        case 200:
          var html = '';
          for (var key in data.response.value.connected) {
            connectionsNum += 1;
            connections.push({ id: data.response.value.connected[key]["id"], nickname: data.response.value.connected[key]["nickname"] });
            html += '<div class="row">';
            html += '<div class="small-6 columns labelPaddingTop"><label title="' + data.response.value.connected[key]["nickname"] + '">' + checkStringLength(data.response.value.connected[key]["nickname"], 30) + '</label></div>';
            html += '<div class="small-6 columns"><div class="switch round">' +
              '<input name="connected' + data.response.value.connected[key]["id"] + '" type="radio" value="no" onChange="disconnectUser(' + data.response.value.connected[key]["id"] + ');">' +
              '<label for="connected' + data.response.value.connected[key]["id"] + '" onclick="">' + $("#i18NoLabel").html() + '</label>' +
              '<input name="connected' + data.response.value.connected[key]["id"] + '" type="radio" value="yes" onChange="connectUser(' + data.response.value.connected[key]["id"] + ', \'' + data.response.value.connected[key]["nickname"] + '\');" checked>' +
              '<label for="connected' + data.response.value.connected[key]["id"] + '" onclick="">' + $("#i18YesLabel").html() + '</label>' +
              '<span></span>' +
            '</div></div>';
            html += '</div>';
          }
          for (var key in data.response.value.unconnected) {
            html += '<div class="row">';
            html += '<div class="small-6 columns labelPaddingTop"><label title="' + data.response.value.unconnected[key]["nickname"] + '">' + checkStringLength(data.response.value.unconnected[key]["nickname"], 30) + '</label></div>';
            html += '<div class="small-6 columns"><div class="switch round">' +
              '<input name="connected' + data.response.value.unconnected[key]["id"] + '" type="radio" value="no" onChange="disconnectUser(' + data.response.value.unconnected[key]["id"] + ');" checked>' +
              '<label for="connected' + data.response.value.unconnected[key]["id"] + '" onclick="">' + $("#i18NoLabel").html() + '</label>' +
              '<input name="connected' + data.response.value.unconnected[key]["id"] + '" type="radio" value="yes" onChange="connectUser(' + data.response.value.unconnected[key]["id"] + ', \'' + data.response.value.unconnected[key]["nickname"] + '\');">' +
              '<label for="connected' + data.response.value.unconnected[key]["id"] + '" onclick="">' + $("#i18YesLabel").html() + '</label>' +
              '<span></span>' +
            '</div></div>';
            html += '</div>';
          }
          if (html.length == 0) {
            html = "No connections";
          }
          $("#connectedPlayersPanelContent").html(html);
          break;
        default:
          revealMessageDialog($("#i18GetConnectionsErrorLabel").html(), data.response.responseCode + ": " + $("#i18GetConnectionsErrorDescription").html());
          break;
      }
    } else {
      revealMessageDialog($("#i18GetConnectionsErrorLabel").html(), data);
    }
  }).always(function () {
    consoleLog("getConnectedUsersDone fired");
    $(GLOBAL).trigger("getConnectedUsersDone");
  });
}

function challenge(placeObj) {
  consoleLog("challenge: " + placeObj);
  if (connectionsNum > 0 && localStorage["#nickname"] != null && localStorage["#nickname"].length > 0) {
    var html = '<p>' + $("#i18ChallengeConnectionsDescription").html() + ' <b>' + placeObj.getPlaceResult().name + '</b>.</p>';
    html += '<input type="hidden" id="challengePlayerPlaceObjId" name="challengePlayerPlaceObjId" value="' + placeObj.getPlaceResult().id + '"/>';
    html += '<hr/><div><input id="challengeAllCheckTop" type="checkbox" name="challengeAllCheck"><label for="challengeAllCheckTop" class="lightGrey">' + $("#i18CheckUncheckAllLabel").html() + '</label></input></div>';
    for (key in connections) {
      html += '<div><input type="checkbox" id="challengePlayer' + connections[key]["id"] + '" name="challengePlayer" value="' + connections[key]["id"] + '"><label for="challengePlayer' + connections[key]["id"] + '">' + connections[key]["nickname"] + '</label></input></div>';
    }
    html += '<div><input id="challengeAllCheckBottom" type="checkbox" name="challengeAllCheck"><label for="challengeAllCheckBottom" class="lightGrey">' + $("#i18CheckUncheckAllLabel").html() + '</label></input></div>';
    $("#challengePlayersHtml").html(html);
    $("input:checkbox[name='challengeAllCheck']").change(function () {
      var isChecked = $(this).is(":checked");
      $("input:checkbox[name='challengeAllCheck']").each(function () {
        $(this).prop('checked', isChecked);
      });
      $("input:checkbox[name='challengePlayer']").each(function () {
        $(this).prop('checked', isChecked);
      });
    });
    revealDialog("#challengePlayersModal");
  } else {
    revealMessageDialog($("#i18NoConnectionsLabel").html(), $("#i18NoConnectionsDescription").html());
  }
}

/**
 * Challenge the selected players.
 */
function challengePlayer() {
  consoleLog("challengePlayer");
  var nickname = "";
  var ids = [];
  $("input:checkbox[name='challengePlayer']").each(function () {
    if($(this).is(":checked")) {
      consoleLog("Challenge: " + $(this).val());
      ids.push($(this).val());
    }
  });

  if (ids.length > 0) {
    revealProcessingDialog();
    var placeObj = placesObjArray[$("#challengePlayerPlaceObjId").val()];

    consoleLog("challengePlayer fired");
    $(GLOBAL).trigger("challengePlayer");
    ajaxCall("/api/v1/challenge.php", {
      uuid: localStorage["uniqueId"],
      ids: ids,
      name: placeObj.getPlaceResult().name,
      vicinity: placeObj.getPlaceResult().vicinity,
      lat: placeObj.getLat(),
      lng: placeObj.getLng()
    }).fail(function (data) {
      consoleLog("challengePlayer error: " + data);
    }).done(function (data) {
      if (data.response != undefined) {
        if (data.response.responseCode == 200) {
          revealMessageDialog($("#i18ChallengeSendLabel").html(), $("#i18ChallengeSendDescription").html());
        } else {
          consoleLog("challengePlayer responsCode error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
        }
      } else {
        consoleLog("challengePlayer error unexpected response: " + data);
      }
    }).always(function () {
      consoleLog("challengePlayerDone fired");
      $(GLOBAL).trigger("challengePlayerDone");
    });
  }
}

/**
 * Show challenges count in menu. Also fill the dialog triggered by the counter with
 * the relevant challenges.
 */
function showChallengesCount() {
  consoleLog("showChallengesCount");
  $(GLOBAL).trigger("showChallengesCount");
  ajaxCall("/api/v1/getChallenges.php", {
    uuid: localStorage["uniqueId"],
    ungrouped: true
  }).fail(function (data) {
    consoleLog("showChallengesCount error: " + data);
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        var challengesCount = data.response.value.places.length;
        consoleLog("Challenges count: " + challengesCount);
        if (challengesCount > 0) {
          $(".challengesCount").html(challengesCount);
          $(".challengesMenu").show();
        } else {
          $(".challengesMenu").hide();
        }
        var html = '<div>';
        for (var key in data.response.value.places) {
          html += '<hr/>';
          html += '<label class="labelPaddingTop" onClick="google.maps.event.trigger(markersObjArray[' + data.response.value.places[key]["id"] + '], \'click\');">';
          if (data.response.value.places[key]["nickname"].length > 0) {
            html += '<span style="color: #' + argbToRGB(hashCode(data.response.value.places[key]["nickname"])) + '">';
            html += data.response.value.places[key]["nickname"];
            html += '</span> ';
          } else {
            html += '<span>';
            html += $("#i18AnonymousPlayerLabel").html();
            html += '</span>';
          }
          html += $("#i18ChallengesYouToVisitLabel").html();
          html += ' <b>';
          html += data.response.value.places[key]["name"];
          html += '</b>, ';
          html += data.response.value.places[key]["vicinity"];
          html += '</label> <a href="javascript: void(0);" onClick="declineChallenge(' + data.response.value.places[key]["id"] + ');"><small>[' + $("#i18DeclineLabel").html() + ']</small></a>';
        }
        html += '</div>';
        $("#challengedByHtml").html(html);
      } else {
        consoleLog("getChallenges responsCode error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
      }
    } else {
      consoleLog("getChallenges error unexpected response: " + data);
    }
  }).always(function () {
    consoleLog("showChallengesCountDone fired");
    $(GLOBAL).trigger("showChallengesCountDone");
  });
}

function declineChallenge(challengeId) {
  consoleLog("declineChallenge: " + challengeId);
  $(GLOBAL).trigger("declineChallenge");
  ajaxCall("/api/v1/declineChallenge.php", {
    uuid: localStorage["uniqueId"],
    id: challengeId
  }).fail(function (data) {
    consoleLog("declineChallenge error: " + JSON.stringify(data));
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        showChallengesCount();
      } else {
        consoleLog("declineChallenge responsCode error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
      }
    } else {
      consoleLog("declineChallenge error unexpected response: " + data);
    }
  }).always(function () {
    consoleLog("declineChallengeDone fired");
    $(GLOBAL).trigger("declineChallengeDone");
  });
}

function assemble(placeObj) {
  consoleLog("assemble");
  // Trigger event.
  $(GLOBAL).trigger('assemble');
  consoleLog("assemble fired");

  $(".assembleButton").html("<img src='img/smallLoader.gif'/>");

  ajaxCall("/api/v1/assemble.php", {
    uuid: localStorage["uniqueId"],
    name: placeObj.getPlaceResult().name,
    vicinity: placeObj.getPlaceResult().vicinity,
    lat: placeObj.getLat(),
    lng: placeObj.getLng()
  }).fail(function (data) {
    consoleLog("assemble error: " + JSON.stringify(data));
  }).done(function (data) {
    if (data.response != undefined) {
      if (data.response.responseCode == 200) {
        revealMessageDialog($("#i18AssembleSendLabel").html(), $("#i18AssembleSendDescription").html());
        placeObj.loadPoints();
      } else {
        consoleLog("assemble responsCode error: " + data.response.responseCode + ":" + data.response.message + " : " + data);
      }
    } else {
      consoleLog("assemble error unexpected response: " + data);
    }
  }).always(function () {
    // Trigger event.
    consoleLog("assembleDone fired");
    $(GLOBAL).trigger('assembleDone');
  });
}