00_danner_fodbolddata

## Danner fodbold data

## Indlæsning af pakker og sætter parametre for api

rm(list = ls())

library(pacman)
p_load(tidyverse, lubridate, httr, jsonlite, 
       devtools, janitor, stringr, httr2, here)

# key <- secret_make_key()

base_url <- "https://api-football-v1.p.rapidapi.com/v3"

header <- c("X-RapidAPI-Host" = "api-football-v1.p.rapidapi.com",
            "X-RapidAPI-Key" = secret_decrypt(Sys.getenv("PASS"), "FODBOLD_KEY"))

ny_geo_url <- "https://geography2.p.rapidapi.com"

ny_geo_headers <- c("X-RapidAPI-Host" = "world-geography2.p.rapidapi.com",
                    "X-RapidAPI-Key" = secret_decrypt(Sys.getenv("PASS"), "FODBOLD_KEY"))

## Finder Tyskland 
## League info: 78, 79 og 80
## Pokal: 81
## Regionalliga: 83, 84, 85, 86, 87

## Finder Danmark
# league: 119

## Finder Belgien
# league: 144

liga_get <- tibble(liga_id = c(78, 79, 80, 83, 84, 85, 86, 87, 119, 144),
                   get = list(NULL),
                   response = list(NULL))


for (i in 1:nrow(liga_get)) {
  
  liga_get$get[[i]] <- request(paste(base_url,
                                     paste0("fixtures",
                                            "?league=",
                                            liga_get$liga_id[i],
                                            "&season=2025"),
                                     sep = "/")) %>% 
    req_headers(!!!header) %>% 
    req_perform()
  
  liga_get$response[[i]] <- liga_get$get[[i]] %>% 
    resp_body_string() %>% 
    fromJSON() %>% 
    pluck("response") %>% 
    as_tibble()
  
}

kampprogram_fulddata <- bind_rows(liga_get$response)

## Sætter danske lokale
Sys.setlocale("LC_TIME", "da_DK")
Warning in Sys.setlocale("LC_TIME", "da_DK"): OS reports request to set locale
to "da_DK" cannot be honored
[1] ""
kampprogram <- kampprogram_fulddata %>% 
  rowwise() %>% 
  mutate(runde = str_extract(league$round, 
                             "(?<=- ).+"), 
         stadie = str_extract(league$round,
                              ".+(?= -)"),
         aar = paste(league$season, league$season+1, sep = "/"),
         liga_id = league$id,
         liga = league$name,
         land = league$country,
         kampdato = date(fixture$date),
         kamptidspunkt = if_else(fixture$status$short == "TBD", 
                                 "TBA",
                                 format(
                                   with_tz(
                                     as_datetime(fixture$date, tz = fixture$timezone),
                                     tzone = "Europe/Berlin"), 
                                   "%H:%M")),
         ugedag = wday(kampdato, label = TRUE, abbr = FALSE, locale = "da_DK.UTF-8", week_start = 1),
         ugedag_nr = wday(kampdato, week_start = 1),
         kampuge = if_else(ugedag_nr == 1, isoweek(kampdato)-1, isoweek(kampdato)),
         weekend = if_else(ugedag_nr %in% c(1, 5, 6, 7), TRUE, FALSE),
         kamp = paste(teams$home$name, teams$away$name, sep = " - "),
         hjemmehold = teams$home$name,
         udehold = teams$away$name,
         spilleby = fixture$venue$city,
         stadion = fixture$venue$name,
         kampstatus = fixture$status$long,
         kamp_id = fixture$id,
         stadion_id = fixture$venue$id,
         timestamp = fixture$date,
         .keep = "none") %>% 
  distinct() %>% 
  ungroup() %>% 
  mutate(fiktiv_kamprunde = dense_rank(pick(kampuge, weekend)), .after = "weekend") %>% 
  ## Specifikt for tysk liga
  mutate(kamptidspunkt = if_else(liga == "3. Liga" & runde != "38" & min(timestamp) == max(timestamp), 
                                 "TBA", 
                                 kamptidspunkt),
         .by = c("runde", "liga_id")) %>% 
  mutate(min_ugedag = if_else(kampdato == min(kampdato), kampdato, NA), .by = fiktiv_kamprunde) %>% 
  group_by(fiktiv_kamprunde) %>%
  fill(min_ugedag, .direction = "downup") %>% 
  ungroup() %>% 
  arrange(runde, match(liga, "Bundesliga")) %>% 
  nest(.by = land) %>% 
  mutate(timestamp_selv = Sys.time())


write_rds(kampprogram, here("fodbold_kalender", "data", "kampprogram.rds"))