# https://github.com/hrbrmstr/slackr
# https://api.slack.com/methods

ensure_poundsign <- function(x) {
  if (!length(x) || any(is.na(x)) || any(!nchar(x))) {
    stop("invalid channel name") ## previously had this as warning
    return(x)
  }
  paste0("#", removeText("#", x))
}


gg_to_slack <- function(
    Plot_object
  , f.out=ggsave.out(plot=Plot_object, nm=removeText("[Pp]\\.", clean.capture.output(substitute(Plot_object))))
  # , f.out=ggsave.out(plot=substitute(Plot_object))
  , comment="look, a graph from R!"
  , title=topropper_keywords(removeExt(basename(f.out), allow_dots_in_ext=FALSE))
  , channels = getOption("slack_default_channel")
) {
  
  if (!missing(Plot_object) && !missing(f.out))
    warning("Plot_object is ignored when f.out is explicit")

  print(f.out)

  channels %<>% ensure_poundsign

  modchan <- slackr_chtrans(channels=channels)
  res <- {
        POST(url = "https://slack.com/api/files.upload"
            , add_headers(`Content-Type` = "multipart/form-data")
            , body = list(
                file = upload_file(f.out)
              , token = getOption("slack_apitoken")
              , channels = modchan
              , title = title
              , filetype = extractExt(f.out)
              , filename = basename(f.out)
              , initial_comment = comment
            )
          )
        }
  return(invisible(res))
}


initialize_slack <- function() {
  lib(slackr)
  lib(ggplot2)
  lib(httr)

  options(slack_default_channel="#slackr-testing")
  options(slack_webhook="https://hooks.slack.com/services/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")
  options(slack_apitoken="xoxp-2467085547-2784010377-21404645603-1db314e681")
  options(slack_username="rick")

  ## Alternatively, this information can go into a file in 
  ##  ~/.slackr
  ##
  #    api_token: YOUR_FULL_API_TOKEN
  #    channel: #general
  #    username: slackr
  #    incoming_webhook_url: https://hooks.slack.com/services/XXXXX/XXXXX/XXXXX

  slackrSetup(
              channel=ensure_poundsign(getOption("slack_default_channel"))
            , username=getOption("slack_username")
            , api_token=getOption("slack_apitoken")
            , incoming_webhook_url=getOption("slack_webhook")
            )
}

## EXAMPLES 
if (FALSE)
{

  ## Send text output to slack
  slackr("test", username="@slackbot")

  ## You can specify a channel, but the channel cannot be private
  slackr("testing slack API (please ignore)", channel="#data")
  slackr("test 3", channel="#slackr-testing")

  ## Send a plot!! to Slack
  ggslackr(qplot(mpg, wt, data=mtcars))
  ggslackr(qplot(mpg, wt, data=mtcars), channel="#data")

  ## ALTERNATIVE USING MY WRAPPER
  # Note that using f.out directly, or using the Plot_object have similar outputs
  # using f.out allows for greater control of the non-default ggsave.out
  # otherwise, identical

  # 1. Using the P object
  P.testing_slacker_connex <- qplot(mpg, wt, data=mtcars)
  gg_to_slack(P.testing_slacker_connex, comment="using the plot object")

  # 2. Manually saving the P object to a file, then using the f.out argument
  f.out <- ggsave.out(P.testing_slacker_connex)
  gg_to_slack(f.out=f.out, comment="using filename")

  # 3. Direct, on-the-fly
  gg_to_slack(qplot(mpg, wt, data=mtcars), comment="Using on the fly plotting")


} ## // end of if (FALSE)
