#### Setup ####
# Load packages
library(tidyverse) # All the tidy things
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   4.0.0     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.1.0     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(jsonlite)  # Converting json data into data frames
## 
## Attaching package: 'jsonlite'
## 
## The following object is masked from 'package:purrr':
## 
##     flatten
library(magrittr)  # Extracting items from list objects using piping grammar
## 
## Attaching package: 'magrittr'
## 
## The following object is masked from 'package:purrr':
## 
##     set_names
## 
## The following object is masked from 'package:tidyr':
## 
##     extract
library(httr)      # Interacting with HTTP verbs

#### Intro ####
# This API is useful because you can connect to see which events are going on
# in the desired city you are in. As well it provides extra details that the 
# ticketmaster website does not give you

# variables needed
# api_key = YOUR api key
# zip = any zip you want to look at
# country = US
# size = 200
# page = 0
# sort = date,asc

tm_api_GET_url <- 
  function(api_key, country, size, page, sort) {
    tm_endpoint <- "https://app.ticketmaster.com/discovery/v2/events.json?"
    
    api_key <- paste("apikey=",api_key, sep = "")
    
    country <- paste("&countryCode=", country, sep = "")
    
    size <- paste("&size=", size, sep = "")
    
    page <- paste("&page=", page, sep = "")
    
    sort <- paste("&sort=", sort, sep = "")
    
    tm_api_GET <- 
      paste(tm_endpoint, api_key, country, size, page, sort, sep = "")
    
    return(tm_api_GET)
  }

#### Calling Data ####
tm_api_GET_url(api_key = "BE6M2fykc97LL2XITU0Q1KJK8Q0GL3BL",
               country = "US",
               size = 200,
               page = 0,
               sort = "date,asc")         # date.asc
## [1] "https://app.ticketmaster.com/discovery/v2/events.json?apikey=BE6M2fykc97LL2XITU0Q1KJK8Q0GL3BL&countryCode=US&size=200&page=0&sort=date,asc"
#### getting dataframe ####
tm_api_GET_df <- 
  function(api_key, country, size, page, sort) {
    tm_api_url <- tm_api_GET_url(api_key, country, size, page, sort)
    
    ticketmaster_df <- 
      tm_api_url %>% 
      GET() %>% 
      content(as = "text",
              encoding = "UTF-8") %>% 
      fromJSON() %>% 
      use_series(`_embedded`) %>% 
      use_series(events)
    
    return(ticketmaster_df)
    
  }
tm_events <- 
  tm_api_GET_df(api_key = "BE6M2fykc97LL2XITU0Q1KJK8Q0GL3BL",
                country = "US",
                size = 200,
                page = 0,
                sort = "date,asc")


#### Looping through Multiple Pages ####
for (i in 2:5) {
  tm_events <- 
    tm_api_GET_df(api_key = "BE6M2fykc97LL2XITU0Q1KJK8Q0GL3BL",
                  country = "US",
                  size = 200, 
                  page = i-1,
                  sort = "date,asc") %>% # Subtract 1 from i to start at page 0!
    bind_rows(tm_events)
  
  # Humans love status messages!
  # Give the user regular progress updates, otherwise it may look like the 
  # request has crashed.
  paste("Page",i,"of","5","collected", sep = " ") %>% 
    print()
  
  # Be gentle to the API! 
  # Add a sleep function at the end of each looping iteration before the last
  # request to accommodate any rate limits. If no rate limit is specified in the
  # documentation, a good rule is to sleep for a few seconds between requests.
  if (i<5) {
    Sys.sleep(3)
  }
}
## [1] "Page 2 of 5 collected"
## [1] "Page 3 of 5 collected"
## [1] "Page 4 of 5 collected"
## [1] "Page 5 of 5 collected"
#### Visuals ####
# visual that shows how many eevents have safe ticketing enables
# This visual shows the distribution of events that are proteted with a 
# changing barcode. This protects people from screenshotting the ticket barcode
# and sending it to someone else
tm_events$ticketing$safeTix %>%
  filter(!is.na(enabled)) %>%
  ggplot(aes(x = enabled))+
  geom_bar()+
  labs(title = "Distribution of Events that are Protected with Bar Code Changing data",
       x = "TRUE/FALSE",
       y = "Count")

# visual that shows how many events have all inclusive pricing like fees
# this visual shows how many events display their pricing and fees upfront.
tm_events$ticketing$allInclusivePricing %>% 
  filter(!is.na(enabled)) %>% 
  ggplot(aes(x = enabled))+
  geom_bar()+
  labs(title = "distribution of Events that contain pricing that displays fees before purchase",
       x = "TRUE/FALSE",
       y = "Count")

# Average events where safe tickeing, and all inclusive pricing is enabled
# this table shows us how many events show are listed NA under safe ticketing
# fields and allinclusive pricing. This tells us how reliable the data is. 
# Right now, there are about 60% NAs in the safe ticketing field and 
# 42% NAs in the all inclusive pricing. This is worth flagging because 
# ticketmaster does not apply data to all of their events.
# What is worth invesigating are the events flagged with no ticket barcode 
# protection. 
tm_events %>%
  summarise(
    safetix_na  = mean(is.na(ticketing$safeTix$enabled)),
    safetix_yes = mean(ticketing$safeTix$enabled %in% TRUE),
    aip_na      = mean(is.na(ticketing$allInclusivePricing$enabled)),
    aip_yes     = mean(ticketing$allInclusivePricing$enabled %in% TRUE))
##   safetix_na safetix_yes aip_na aip_yes
## 1      0.626       0.235  0.424   0.491
#### Creating new data frame that pulls events with no ticket protection ####
# This helps look at the events and determine how many events do not have this
# protection help. To further enhance this anaysis, i can add a city field to 
# my API URL function to pull the events with no ticket protection by city. 

# To ticketmaster this is an internal control issue because a average person 
# like me can connect to their API to see which events do not have a ticket
# protection on that event. Someone with unethical prinicples could exploit
# this by screenshotting the bar code on his ticket and sending it to his/her 
# friends... Assuming the API is telling the truth.
false_safe_tix <- 
  tm_events %>% 
  filter(tm_events$ticketing$safeTix$enabled == FALSE)