const debug = require("debug")("test");
const Model = require("../models")
const service = require("../services/AppService");
let livePlayers = [];

function getPlayer() {
  return livePlayers;
}
function isExistUser(data) {
  let count = 0;
  // livePlayers.forEach((element, index, array) => {
  //   if (element["playerId"] == data.playerId) {
  //     count++;
  //   }
  // });
  for(let value of livePlayers){
    if(value.playerId == data.playerId){
      count++;
    }
  }

  if (count == 0) {
    return false;
  } else {
    return true;
  }
}

function registerToLobby(data) {
  //  console.log("----------",data)
  let status = 1;
  let count = 0;
  // livePlayers.forEach((element, index, array) => {
  //   if (element["playerId"] == data.playerId) {
  //     count++;
  //   }
  // });
  for(let value of livePlayers){
    if(value.playerId == data.playerId){
      count++;
    }
  }
  //  debug(livePlayers);
  if (count == 0) {
    data.friendRequest = [];
    livePlayers.push(data);
    // service.changeStatus(status, data.playerId);
    debug("player ID " + data.playerId + " enter in lobby");
  }
}
function exitToLobby(socketId) {
  let status = 0;
  for (let i = 0; i < livePlayers.length; i++) {
    if (livePlayers[i].socketId == socketId) {
      // service.changeStatus(status, livePlayers[i].playerId);
      debug("player ID " + livePlayers[i].playerId + " leave from lobby");
      livePlayers.splice(i, 1);
      return;
    }
    debug("player not found");
  }
}
function getUser(playerId) {
  // livePlayers.forEach((element, index, array) => {
  //   if (element["playerId"] == playerId) {
  //    return element;
  //   }
  // });
  // find playerId in livePlayers
  for (let i = 0; i < livePlayers.length; i++) {
    if (livePlayers[i].playerId === playerId) {
      return livePlayers[i];
    }
  }
  return null;
}
function updateUser(playerId, socket){
  for (let i = 0; i < livePlayers.length; i++) {
    if (livePlayers[i].playerId === playerId) {
      return livePlayers[i].socket = socket;
    }
  }
}
async function addFriends(player, newFriend = null) {
  try {
    livePlayers.forEach((livePlayer, index) => {
      if (livePlayer.playerId === player.playerId) {
        livePlayers[index] = player;
      }
      if (newFriend) {
        if (livePlayer.playerId === newFriend.playerId) {
          livePlayers[index] = newFriend;
        }
      }
    });
  } catch (err) {
    console.error(err);
  }
}
async function tatalcheck (){

  let totalplayer = livePlayers.length
  // console.log(livePlayers,totalplayer)
  return totalplayer
}
module.exports = { getPlayer, registerToLobby, exitToLobby, isExistUser, getUser, addFriends, livePlayers ,tatalcheck, updateUser };
