##https://trends.google.com/trends/explore?date=today%203-m&q=bitcoin
read_googletrend_file<-function(data_file="googleTrendsData90DaysBitcoin.csv",default_dir="https://skipcrooker.com/PA4MBA/chapter_04/")
{
  my_data<-read.csv(paste0(default_dir,data_file),header=TRUE,skip=2)
  if (names(my_data)[1]=="Month") {
    my_data$Month<-as.Date(paste0(as.character(my_data$Month),"-01"))
  }
  y<-xts(my_data[,2],order.by=as.Date(as.character(my_data[,1])) )
  return(y)
}
search_interest_by_day_plot<-function(Data=read_googletrend_file(),title="Bitcoin Searches",alt_y_title="Search Interest")
{
  my_weekdays<-c("Monday","Tuesday","Wednesday","Thursday","Friday",
                 "Saturday","Sunday")
  
  Ordered_Daily<-match(format(index(Data),"%A"),my_weekdays)
  Ordered_Daily<-factor(Ordered_Daily,levels=1:7,labels=substr(my_weekdays,1,3))
  
  plot(x=Ordered_Daily,
       y=as.numeric(Data),
       xlab="Day of Week",
       ylab=alt_y_title,
       main=title)
}
search_interest_by_month_plot<-function(Data=read_googletrend_file(),title="Bitcoin Searches",alt_y_title="Search Interest")
{
  Ordered_Monthly<-as.numeric(substr(index(Data),6,7))
  Ordered_Monthly<-factor(Ordered_Monthly,levels=1:12,labels=month.abb)
  
  plot(x=Ordered_Monthly,
       y=as.numeric(Data),
       xlab="Month of Year",
       ylab=alt_y_title,
       main=title)
}
search_interest_plot<-function(Data=read_googletrend_file(),title="Bitcoin Searches",alt_y_title="Search Interest")
{
  dow_table<-table(format(index(Data),"%A"))
  if (length(names(dow_table))<7) {
    Ordered_Data<-as.numeric(substr(index(Data),6,7))
    Ordered_Data<-factor(Ordered_Data,levels=1:12,labels=month.abb)
    my_xlab<-"Month of Year"
  } else {
    my_weekdays<-c("Monday","Tuesday","Wednesday","Thursday","Friday",
                   "Saturday","Sunday")
    
    Ordered_Data<-match(format(index(Data),"%A"),my_weekdays)
    Ordered_Data<-factor(Ordered_Data,levels=1:7,labels=substr(my_weekdays,1,3))
    my_xlab<-"Day of Week"
  }
  plot(x=Ordered_Data,
       y=as.numeric(Data),
       xlab=my_xlab,
       ylab=alt_y_title,
       main=title)
}
available_google_trend_periods<-function()
{
  google_trend_search_params<-list(past_hour="explore?date=now%201-H&q=bitcoin",
                                   past_4_hours="explore?date=now%204-H&q=bitcoin",
                                   past_day="explore?date=now%201-d&q=bitcoin",
                                   past_7days="explore?date=now%207-d&q=bitcoin",
                                   past_30days="explore?date=today%201-m&q=bitcoin",
                                   past_90days="explore?date=today%203-m&q=bitcoin",
                                   past_12mon="explore?q=bitcoin",
                                   past_5yr="explore?date=today%205-y&q=bitcoin",
                                   since_2004="explore?date=all&q=bitcoin")
  
  my_descriptions<-c("Past hour",
                     "Past 4 hours",
                     "Past day",
                     "Past 7 days",
                     "Past 30 days",
                     "Past 90 days",
                     "Past 12 months",
                     "Past 5 years",
                     "Since 2004")
  
  my_df<-data.frame(trend_period_code=names(google_trend_search_params),Description=my_descriptions)
  return(my_df)
}
selenium_google_trends_csv<-function(term="bitcoin",trend_period="past_12mon",default_download_info=NULL)
{
  ### This script will download the trends data to the default directory as: multiTimeline.csv
  ###
  ### To rename the downloaded file use:
  ###
  ###    default_download_info<-list(directory="C:/User/Downloads/",new_directory="C:/google_trends/")
  ###
  
  google_trend_search_params<-list(past_hour="explore?date=now%201-H&q=bitcoin",
                                   past_4_hours="explore?date=now%204-H&q=bitcoin",
                                   past_day="explore?date=now%201-d&q=bitcoin",
                                   past_7days="explore?date=now%207-d&q=bitcoin",
                                   past_30days="explore?date=today%201-m&q=bitcoin",
                                   past_90days="explore?date=today%203-m&q=bitcoin",
                                   past_12mon="explore?q=bitcoin",
                                   past_5yr="explore?date=today%205-y&q=bitcoin",
                                   since_2004="explore?date=all&q=bitcoin")
  
  search_params<-NULL
  try(search_params<-google_trend_search_params[[trend_period]])
  if (is.null(search_params)) {
    search_params<-google_trend_search_params[["past_12mon"]]
    trend_period="past_12mon"
  }
  search_params<-gsub("bitcoin",term,search_params)
  
  require(RSelenium)
  if (!("rD" %in% objects())) {
    rD<-rsDriver(port=4567L,browser="chrome",verbose=FALSE)
    mybrowser<-rD[["client"]]
  }
  mybrowser$navigate(paste0("https://trends.google.com/trends/",search_params))
  ### Pause 6 to 10 seconds to allow the page to load
  Sys.sleep(5*ceiling(runif(1))+5)
  ### Done pausing.
  my_buttons<-mybrowser$findElements("tag name","button")
  ## This will download the csv file to the default download directory.
  my_buttons[[10]]$clickElement()
  ### Rename downloaded file if default_download_info is not NULL
  ### Pause 6 to 10 seconds to allow the data to download
  Sys.sleep(5*ceiling(runif(1))+5)
  my_file<-"multiTimeline.csv"
  ### Done pausing.
  if (!is.null(default_download_info)) {
    my_time<-gsub("[: ]","",Sys.time())
    my_file<-paste0(default_download_info$new_directory,"google_trends_",term,"_",trend_period,"_",my_time,".csv")
    file.rename(from=paste0(default_download_info$directory,"multiTimeline.csv"),
                to=my_file)
  }
  ### Close Selenium Server
  mybrowser$close()
  rm(rD)
  garbage<-gc()
  return(my_file)
}