```{r}
library(tidyverse)
library(spotifyr)
token <- read.csv("data/spotify_token")
Sys.setenv(SPOTIFY_CLIENT_ID = token[1, 1])
Sys.setenv(SPOTIFY_CLIENT_SECRET = token[1, 2])
```

```{r}
access_token <- get_spotify_access_token()
```

```{r}
# given album name and singer name, get album's tracks data 
get_tracks_data <- function(album_name, singer) {
  res <- search_spotify(paste(album_name, singer, sep = ", "), type = "album")[1, 5] %>%
    get_album_tracks()
  ids <- res$id

  # Popularity
  pop <- get_tracks(ids) %>%
    select(
      track_id = id,
      duration_ms,
      name,
      popularity,
    )

  # Audio features
  feature <- data.frame()
  for (id in ids) {
    tryCatch({
      track_feature <- get_track_audio_features(id) %>%
        select(
          track_id = id,
          acousticness,
          danceability,
          energy,
          instrumentalness,
          key,
          liveness,
          loudness,
          mode,
          speechiness,
          tempo,
          time_signature,
          valence
        )
      feature <- rbind(feature, track_feature)
    }, error = function(e) {
      print('TRACK LOST')
    })
  }

  df1 <- merge(pop, feature, by = "track_id", all.x = TRUE)

    # group_by(album.name) %>%
    # summarise(
    #   avg_pop = mean(popularity),
    #   max_pop = max(popularity),
    #   sum_pop = sum(popularity),
    #   n = n()
    # )
  return(df1)
}
```

```{r}
# given album name and singer name, get stream popularity
get_album_data <- function(album_name, singer) {
  res <- search_spotify(paste(album_name, singer, sep = ", "), type = "album")[1, 5] %>%
    get_album_tracks()
  res <- get_tracks(res$id) %>%
    summarise(
      avg_pop = mean(popularity),
      max_pop = max(popularity),
      min_pop = min(popularity),
      med_pop = median(popularity),
      n = n()
    )
  return(res)
}
```

```{r}
# for music in metacritic_data.csv get spotify popularity
df <- read.csv("data/meta.csv")
```

```{r eval=F}
spotify_data <- data.frame()
not_matched <- 1:nrow(df)
maxiter <- 1 # increase if too many missing albums
iter <- 1
while (iter <= maxiter) {
  not_matched_new <- NULL
  for (i in not_matched) {
    album_name <- df[i, "Album_Name"]
    singer <- df[i, "Singer"]
    tryCatch({
      row <- get_album_data(album_name, singer)
      row$id <- df[i, 'id']
      spotify_data <- rbind(spotify_data, row)
      print(c(i, '✅', singer, album_name))
    }, error = function(e) {
      not_matched_new <<- c(not_matched_new, i)
      print(c(i, '❌', singer, album_name))
    })
  }
  not_matched <- not_matched_new
  iter <- iter + 1
}
```

```{r, eval=F}
# export to csv
write.csv(spotify_data, "data/spotify_new.csv", row.names = FALSE)
```

```{r}
tracks_data <- data.frame()
track_not_matched <- 1:nrow(df)
maxiter <- 1 # increase if too many missing albums
iter <- 1
while (iter <= maxiter) {
  track_not_matched_new <- NULL
  for (i in track_not_matched) {
    album_name <- df[i, "Album_Name"]
    singer <- df[i, "Singer"]
    tryCatch({
      rows <- get_tracks_data(album_name, singer)
      rows$id <- df[i, 'id']
      tracks_data <- rbind(tracks_data, rows)
      print(c(i, '✅', singer, album_name))
    }, error = function(e) {
      track_not_matched_new <<- c(track_not_matched_new, i)
      print(c(i, '❌', singer, album_name))
    })
  }
  track_not_matched <- track_not_matched_new
  iter <- iter + 1
}
```

```{r}
# export to csv
write.csv(tracks_data, "data/spotify_tracks.csv", row.names=FALSE)
```