#' Similar players
#' 
#' @aliases do_similar_players
#'
#' @description 
#' For a player of interest, set of the similar players regarding
#' every archetypoid.
#' 
#' @usage 
#' do_similar_players(player, alphas, numArchoid, allArchoid = TRUE)
#' 
#' @param player Player of interest.
#' @param alphas Matrix of alphas.
#' @param numArchoid Number of archetypoids.
#' @param allArchoid Logical. If TRUE, all the archetypoids are used
#' to create the set of similar platers.
#' 
#' @note 
#' If \code{allArchoid = FALSE}, we propose the following procedure to choose 
#' the group of analogous players: for each archetypoid, we choose a number of 
#' players proportional to the corresponding target player's alpha. These players 
#' have an alpha between the archetypoid and the target player. For instance, if 
#' the player's alpha for archetypoid is 0.5, and there are eight players between 
#' him and the archetypoid, we choose the first four. Thus, we take into account 
#' the similarity of the player for every archetypoid, not just with the one who 
#' shares the greatest alpha.
#' 
#' @return 
#' A vector with the similar players.
#' 
#' @author 
#' Guillermo Vinue
#'
#' @examples 
#' # See the code.
#' 
#' @export

do_similar_players <- function(player, alphas, numArchoid, allArchoid = TRUE){
  
  if (allArchoid) {
    pos <- which(colnames(alphas) %in% player)
    sim_pl <- c()
    for (i in 1:numArchoid) {
      alpha_order <- order(alphas[i,], decreasing = TRUE)
      alpha_pos <- which(alpha_order == pos)
      num_pl <- trunc(alphas[i,pos] * alpha_pos)
      # Instead of using 1:num_pl, we use seq_len(num_pl) to avoid the backwards sequence bug 1:0.
      # https://www.r-bloggers.com/r-tip-use-seq_len-to-avoid-the-backwards-sequence-bug/
      # Then, the archetypoid with alpha=0 don't appear in the set of similar players:
      pl <- names(sort(alphas[i,], decreasing = TRUE)[seq_len(num_pl)])
      sim_pl <- c(sim_pl, pl)
    }
    # In order to predict a player's metric we have to use the trajectory of 
    # the similar players plus that player:
    sim_pl1 <- c(sim_pl, player)
    sim_pl2 <- unique(sim_pl1)  
  }else{
    arch_sim <- which.max(alphas[, grep(player, colnames(alphas))])
    sort_pl <- names(sort(alphas[arch_sim,], decreasing = TRUE))
    num_pl_sim <- which(sort_pl == player)
    sim_pl2 <- sort_pl[1:num_pl_sim]
  }
  
  return(sim_pl2)
}
