var ws;

var userName = ""

window.onload = function() {

  'use strict';

  function getRandomInt(max) {
    return Math.floor(Math.random() * Math.floor(max));
  }

  var LobbyList = Backbone.View.extend({

    lobbies: undefined,

    initialize: function () {
      this.elCount = 0;
    },

    template: _.template('<table id ="deciderList" class="table"><tbody><tr>\n' +
        '                <th>Host</th>\n' +
        '                <th>Status</th>\n' +
        '                <th>Action</th></tr>\n' +
        '            </tbody></table>'),

    events: {
      "click .title": "check" // Обработчик клика на кнопке "Проверить"
    },

    joinAsPlayer: function () {
      this.elCount = "azaz" + getRandomInt(100000000);
      this.render();
    },

    render: function() {

      var lobbiesAsTableRows = _.reduce(this.lobbies, function (memo, lobby) {

        var joinButton = (lobby.status === "NotStarted()") ? '<button class="btn btn-primary join-as-player" onclick="joinDecider(\''+lobby.lobbyActorName+'\')">' +
            '<img src="assets/images/buttons/isAuto.png" style="height: 25px;"> Join lobby <img src="assets/images/buttons/isAuto.png" style="height: 25px;">' +
            '</button>' : "";
        var observerButton = '<button class="btn btn-success join-as-observer" onclick="observerDecider(\''+lobby.lobbyActorName+'\')">' +
            '<img src="assets/images/buttons/Ulthwe.png" style="height: 25px;"> Observer <img src="assets/images/buttons/Ulthwe.png" style="height: 25px;">' +
            '</button>';

        return memo + '<tr>\n' +
      '           <td>'+ lobby.user1Info.name +'</td>\n' +
      '           <td>'+ lobby.user2Info.name +'</td>\n' +
      '           <td>'+ lobby.status +'</td>\n' +
      '           <td>' + joinButton + ' ' + observerButton +
            ' </td>' +
        '</tr>';
      }, "");

      var tableStart = '<table id ="deciderList" class="table"><tbody><tr>\n' +
          '                <th>Player1</th>\n' +
          '                <th>Player2</th>\n' +
          '                <th>Status</th>\n' +
          '                <th style="width: 400px;">Action</th></tr>\n';

      var tableEnd = '</tbody></table>';

      var res = tableStart + lobbiesAsTableRows + tableEnd;

      $("#deciderList tbody", res).append(lobbiesAsTableRows);
      console.log(res);

      this.$el.html(res);
    }
  });

  var lobbyList = new LobbyList;
  $("#lobbiesList").append(lobbyList.$el);
  lobbyList.render();

  $("#createDecider").click(function(event) {
    event.preventDefault();
    ws.send(JSON.stringify({
      type: "createDecider"
    }));
  });

  $("#updateDecider").click(function(event) {
    event.preventDefault();
    ws.send(JSON.stringify({
      type: "updateDecider"
    }));
  });

  $("#submitmsg").click(function(event) {
    sendMessage();
  });
  $("#usermsg").on('keyup', function (e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
      sendMessage()
    }
  });


  $("#exit").click(function(event) {
    event.preventDefault();
    ws.send(JSON.stringify({
      type: "leaveDecider"
    }));
    $("#decider").hide();
    $("#lobbies").show();
  });

  if($.cookie('user')=== undefined){
    var result = prompt("Enter nickname: ", );
    $.cookie('user', result, { expires: 7 });
    userName = result;
  }else{
    userName = $.cookie('user');
  }

  $("#playerName").html(userName);


  ws = new WebSocket($("body").data("ws-url"));
  ws.onmessage = function(event) {
    var message;
    message = JSON.parse(event.data);
    switch (message.type) {
      case "refreshLobby":
        renderMaps(message.lobby.maps);
        renderPlayersAndStats(message.lobby);
        break;
      case "switchToLobby":
        console.log(message);
        switchToLobby(message.lobby.maps);
        renderPlayersAndStats(message.lobby);
        break;
      case "sendMessage":
        console.log(message);
        addMessageToChat(message.message);
        break;
      case "sendMapBanMessage":
        console.log(message);
        addBanMapMessageToChat(message.message);
        break;
      case "lobbyError":
        console.log(message);
        disconnectLobby(message.error);
        break;
      case "lobbies":
        lobbyList.lobbies = message.lobbies;
        lobbyList.render();
        return console.log(message);
        break;
      default:
    }
  };
  ws.onopen = function () {
    ws.send(JSON.stringify({
      type: "userName",
      name: $.cookie('user')
    }));
  }

  let timerId = setInterval(() =>
      ws.send(JSON.stringify({
        type: "getLobbies"
      })), 2000);
}

function changeNick() {
  result = prompt("Введите ник", $.cookie('user'));
  if(result == null) return;
  $.cookie('user', result, { expires: 7 });
  ws.send(JSON.stringify({
    type: "userName",
    name: $.cookie('user')
  }));

  userName = $.cookie('user');
  $("#playerName").html(userName);

}


// -----ф-ии прихода с сервера

function switchToLobby(maps) {
  console.log(maps);
  renderMaps(maps);
  $("#lobbies").hide();
  $(".navbar").hide();
  $("#decider").show();
  $("#chatbox").html("");
}

function disconnectLobby(error) {
  $("#decider").hide();
  $(".navbar").show();
  $("#lobbies").show();
  alert(error);
}

function renderMaps(maps) {
  var resHtml = "";

  _.each(maps, function (map) {

    var banHtml = "";
    var banClass = "";
    if(map.isBanned){
      banHtml = "<div class = 'banX'>&#x2715;</div>";
      banClass = "bannedMap";
    }



    resHtml = resHtml + '<div class="col-xs-4 col-md-3 col-lg-2"><button class = "mapSelect" onmousedown="banMap(\''+map.map+'\')">'+
        '<div class="mapImageAndText '+banClass+'">' +
        '<img class="img-rounded center-block" style="width:128px;" src="/assets/images/maps/'+encodeURI(map.map)+'.jpg">' +
        '</div>'+convertMapName(map.map)+
        banHtml + '</button></div>';
  })
  $("#mapList").html(resHtml);
}

function renderPlayersAndStats(lobby) {
  var resHtml = "<center>";
  var player1ReadyBtn = "";
  var player2ReadyBtn = "";
  var readyImg = "<img src='/assets/images/buttons/isAuto.png' class='readyImg'/>";
  var notReadyImg = "<img src='/assets/images/buttons/isNotAuto.png' class='readyImg'/>";
  var warningClass = (lobby.user2Info.name !== "") ? "warningButton" : "";

  if(lobby.user1Info.name === userName){
    if(lobby.user1Info.isReady){
      player1ReadyBtn = "<button class='btn btn-default' onclick='setNotReady()'>"+readyImg+" Ready "+readyImg+"</button>"
    }else{
      player1ReadyBtn = "<button class='btn btn-default "+warningClass+"' onclick='setReady()'>"+notReadyImg+" Not ready "+notReadyImg+"</button>"
    }
  }else{
    if(lobby.user1Info.isReady){
      player1ReadyBtn = readyImg
    }else{
      player1ReadyBtn = notReadyImg
    }
  }

  if(lobby.user2Info.name === userName){
    if(lobby.user2Info.isReady){
      player2ReadyBtn = "<button class='btn btn-default' onclick='setNotReady()'>"+readyImg+" Ready "+readyImg+"</button>"
    }else{
      player2ReadyBtn = "<button class='btn btn-default "+warningClass+"' onclick='setReady()'>"+notReadyImg+" Not ready "+notReadyImg+"</button>"
    }
  } else {
    if(lobby.user2Info.isReady){
      player2ReadyBtn = readyImg
    }else{
      player2ReadyBtn = notReadyImg
    }
  }

  if (lobby.user1Info.name === userName || lobby.user2Info.name === userName) {
    $("#inputMsg").show();
  } else {
    $("#inputMsg").hide();
  }

  var lobbyTypeText = "";
  var last3Selected = "";
  var last4Selected = "";
  var looserPickSelected = "";
  switch (lobby.selectedType) {
    case "Last3()":
      last3Selected = "selected";
      lobbyTypeText = "Play on last 3 maps";
      break;
    case "Last4()":
      last4Selected = "selected";
      lobbyTypeText = "Play on last 4 maps";
      break;
    case "LooserPick()":
      looserPickSelected = "selected";
      lobbyTypeText = "Decide first, then looserpick";
      break;
  }

  switch (lobby.status) {
    case "NotStarted()":
      resHtml = "<div style='float: left; padding-top: 10px;'> <div>" + lobby.user1Info.name + ": " +  player1ReadyBtn +"</div><br/>"
      if(lobby.user2Info.name !== ""){
        var kickBtn = ""
        if(lobby.user1Info.name === userName){
          kickBtn = " - <button class='btn btn-danger' onclick='kickSecondPlayer()'>Kick</button>";
        }
        resHtml += "<div>" + lobby.user2Info.name + ": " +  player2ReadyBtn +  kickBtn + "</div>"
      }else{
        resHtml += "<div>waiting 2-nd player...</div>"
      }

      var disabledText = "";


      if(lobby.user1Info.name !== userName){
        disabledText = "disabled";
      }
      resHtml += "<br/><select class=\"form-control\" id = 'deciderOption' onChange='changeLobbyType()' "+disabledText+" >" +
          "<option "+last3Selected+"  value = 'last3'>Play on last 3 maps</option>" +
          "<option "+last4Selected+"  value = 'last4'>Play on last 4 maps</option>" +
          "<option "+looserPickSelected+"  value = 'looserpick'>Decide first, then looserpick</option>" +
          "</select>"
      resHtml += "</div>";
      break;
    case "Draft()":
      console.log(lobby.turn);
      var playerTurn = (lobby.playerTurn === 1) ? lobby.user1Info.name : lobby.user2Info.name
      resHtml = "<center>"+lobby.user1Info.name + " vs " + lobby.user2Info.name + " - " +lobbyTypeText+ "<br/><b>" + playerTurn +"</b> turn</center>";
      break;
    case "Finish()":
      var lastMaps = _.filter(lobby.maps, function (map){
        return map.isBanned === false;
      });
      resHtml = "<center><b>";
      _.forEach(lastMaps,function (map){
        resHtml += convertMapName(map.map) + "; "
      })
      resHtml += "</b></center>";
  }

  resHtml = resHtml + "</center>"

  $("#playersStatsList").html(resHtml);
}

function addMessageToChat(message){
  var messageHtml = "<div class='msgln'> <b>" + message.userName + "</b>: " + message.message + "<br></div>";
  var chatBox = $("#chatbox");
  chatBox.append(messageHtml);
  chatBox.scrollTop(40000);
}

function addBanMapMessageToChat(message){
  var messageHtml = "<div class='msgln'><span style='color: #2C3D9B'>" + convertMapName(message.mapTechName) + "</span> banned by " + message.user + "<br></div>";
  var chatBox = $("#chatbox");
  chatBox.append(messageHtml);
  chatBox.scrollTop(40000);
}

function banMap(map){
  ws.send(JSON.stringify({
    type: "banMap",
    map: map
  }));
}

function setReady(){
  ws.send(JSON.stringify({
    type: "setReady"
  }));
}

function setNotReady(){
  ws.send(JSON.stringify({
    type: "setNotReady"
  }));
}

function changeLobbyType(){
  var lobbyType = $("#deciderOption").val();
  ws.send(JSON.stringify({
    type: "changeLobbyType",
    lobbyType: lobbyType
  }));
}

function joinDecider(actorName){
  ws.send(JSON.stringify({
    type: "joinDecider",
    lobbyActorName: actorName
  }));
}

function observerDecider(actorName){
  ws.send(JSON.stringify({
    type: "observerDecider",
    lobbyActorName: actorName
  }));
}

function sendMessage(){
  var userInput = $("#usermsg");
  var message = userInput.val();
  userInput.val("");
  if(message !== ""){
    ws.send(JSON.stringify({
      type: "sendMessage",
      message: message
    }));
  }
}

function kickSecondPlayer(){
  ws.send(JSON.stringify({
    type: "kickSecondPlayer"
  }));
}

function convertMapName (techMapName) {
  var mapName = techMapName.replace("2p_", "").replaceAll("_", " ") + " (2)";
  return mapName.charAt(0).toUpperCase() + mapName.slice(1);
}
