# bitly_utils.r  --- used primarilly for AWS shortening

# Default options including id and secreat are in
#    ~/git/misc/rscripts/utils/AWS_Utils/AWS_and_S3_options.r
#    ~/git/misc/rscripts/utils/bitly_utils/bitly_token and credentials.r



if (FALSE) {
  longUrl <- "http://dev-rsaporta.s3.amazonaws.com/justForYou/TESTING/Vodafone_activity.csv?AWSAccessKeyId=AKIAIL4U6IIRF22KG3NA&Expires=1433980567&Signature=qgyrCQLoo6hZ7kpLOXzbO4O7KE8%3D"
  url_shorten(longUrl)
}

url_shorten <- function(longUrl, title=NULL, note=NULL, token=get_bitly_token(), link_to_use=c("link", "aggregate_link"), USE.NAMES=TRUE, encode=TRUE, showWarnings=TRUE) {
## link_to_use :: bitly returns both. aggregate_link := a bitly short URL for the provided longUrl, which can be used to track aggregate stats across all Bitlinks that point to the same longUrl.
##
## Parameters
##   longUrl - the URL to be saved as a Bitlink.
##   title - optional the title of this Bitlink.
##   note - optional a description of, or note about, this Bitlink.
##   private - optional boolean true or false indicating privacy setting (defaults to user-level setting).
##   user_ts - optional timestamp as an integer epoch.

  link_to_use <- match.arg(link_to_use)

  if (length(longUrl) > 1) {
    ARGS <- collectArgs(except="longUrl")
    return(sapply(longUrl, function(u) do.call(url_shorten, c(ARGS, longUrl=u)), USE.NAMES=USE.NAMES))
  }

  if (!is.char_of_length1(longUrl, fail=FALSE))
    return(longUrl)

  optionally_encode <- {. %>% ifelseNULL(., no=trim(ifelse(encode, quickUrlEncode(.), .))) }

  params <- list(
      longUrl = optionally_encode(longUrl)
    , title   = optionally_encode(title)
    , note    = optionally_encode(note)
    , private = 'true'
    , user_ts = as.numeric(now())
    , access_token=token
    )

  sub_url <- "v3/user/link_save"
  url <- as.path(get_bitly_base_url(), sub_url) %>% sprintf("%s?%s", ., list_to_param_string(params, drop=TRUE))

  ## Make the API CALL
  raw <- RCurl::getURL(url)

  if (grepl("404 Not Found", raw)) {
    verboseMsg(showWarnings, "bitly api returned 404 for longUrl = '", longUrl, "'\n\nAPI Call was:    ", url, "\n", call.=FALSE)
    return(longUrl)
  }

  if (grepl("502 Bad Gateway", raw)) {
    verboseMsg(showWarnings, "bitly api returned 502 Bad Gateway error for longUrl = '", longUrl, "'\n\nAPI Call was:    ", url, "\n", call.=FALSE)
    return(longUrl)
  }

  ## PARSE THE RESULTS
  ## Note to self for future use. link_save$new_link represents a BOOLEAN (not a integer)
  j_parsed <- jsonlite::fromJSON(raw)

  if (!USE.NAMES)
    return(j_parsed$data$link_save[[link_to_use]])
  return(setNames(nm=j_parsed$data$link_save$long_url, obj=j_parsed$data$link_save[[link_to_use]]))
}




