#' Function to read tabular (\code{.csv}) data generated by Google's GPS 
#' MyTracks Android app. 
#' 
#' The MyTracks app was discontinued in 2016. 
#' 
#' @param file A vector of file names from Google's MyTracks Android app.
#' 
#' @param verbose Should the function give messages? 
#' 
#' @author Stuart K. Grange
#' 
#' @return Tibble. 
#' 
#' @export
read_my_tracks <- function(file, verbose = FALSE) {
  
  file %>% 
    purrr::set_names(.) %>% 
    purrr::map_dfr(read_my_tracks_worker, verbose = verbose, .id = "file")
  
}


read_my_tracks_worker <- function(file, verbose) {
  
  # A message to the user
  if (verbose) message(threadr::date_message(), "`", file, "`...")
  
  # Load data
  suppressWarnings(
    df <- readr::read_csv(
      file, skip = 2, show_col_types = FALSE, progress = FALSE
    ) 
  )
  
  # Two different types of files
  if (names(df)[1] == "Name") {
    
    # A catch for a corrupted file
    if (df[1, 1, drop = TRUE] == "Split") {
      n_skip <- -1:-3
    } else {
      n_skip <- -1:-2
    }
    
    df <- df %>% 
      slice(n_skip) %>% 
      select(-ncol(.)) %>% 
      purrr::set_names(names(df)[-1]) %>% 
      mutate(across(everything(), ~type.convert(., as.is = TRUE)),
             Time = lubridate::ymd_hms(Time, tz = "UTC"))
    
  }
  
  df <- df   %>% 
    dplyr::rename_with(threadr::str_rm_round_brackets) %>% 
    dplyr::rename_with(threadr::str_to_underscore) %>% 
    rename(date = time) %>% 
    mutate(date = lubridate::force_tz(date, "UTC"),
           time = threadr::calculate_deltas(date, min(date)),
           time = as.numeric(time),
           time = hms::as_hms(time)) %>% 
    select(date,
           latitude,
           longitude,
           altitude,
           speed,
           time)
  
  return(df)
  
}
