library(BAwiR)
library(tidyverse)

load("data_app_acb.RData") # Under request, big file.
df0 <- data_app_acb 

df1 <- df0 %>%
  # There are some players with the same names, so we add the CombinID to distinguish them:
  unite(Player.x, Player.x, CombinID, sep = "~", remove = FALSE)
#df2 <- get_stats_seasons(df1, "ACB", "Doncic, Luka~460", "PIR", "Regular Season")$df_gg
# In the column Age 'days' means 'years'.
#df2 # Compare with http://www.acb.com/stsacumjug.php?cod_jugador=460
#df2 %>%
# arrange(desc(Season)) %>%
# mutate(Age = as.numeric(round(Age)))

players <- sort(as.character(unique(df1$Player.x)))
length(players)
#[1] 2822

df5 <- data.frame()
s0 <- Sys.time()
for (i in 1:length(players)) {
  print(i)
  df2 <- get_stats_seasons(df1, "ACB", players[i], "PIR", "Regular Season")
  if (any(is.na(df2))) { # There are some players who only played playoffs (Alquezar, A.).
    next
  }else{
    df3 <- df2$df_gg
  }
  
  # There were some players who played in several teams the same season:
  if (any(duplicated(df3$Age))) {
    df3_1 <- df3 %>% 
      group_by(Age) %>% 
      mutate(PIR = mean(PIR)) %>% 
      ungroup() %>% 
      distinct(Age, .keep_all = TRUE)
  }else{
    df3_1 <- df3
  }
  
  df4 <- df3_1 %>%
    arrange(desc(Season)) %>%
    mutate(Age = as.numeric(ceiling(Age))) %>%
    #select(Name, PIR, Age)
    select(-Team)
  df5 <- rbind(df5, df4)
}
s1 <- Sys.time() - s0
s1
#Time difference of 17.75756 mins
length(unique(df5$Name))
#[1] 2800
range(df5$Age)
#[1] 15 44
dim(df5)
#[1] 8748    4
write_csv(df5, path = "df_acb.csv")
