#' @title Send a message to a mattermost server
#' 
#' @param msg character, the message to be sent. Each element is a considered as
#'  a line.
#' @param server character, the address of the mattermost server.
#' @param hook character, the ID of the webhook defined in the mattermost
#'  server.
#' @param user character, the name of the user.
#' @param channel character, the ID of the channel. Default to NULL, in that
#'  case, the default channel defined at mattermost server level fot the webhook
#'  will be used.
#' @param alert logical, should the alert be send to the mattermost server.
#' 
#' @return If alert is FALSE, the command generated to send the message.
#' 
#' @export alert_mattermost
#'
#' @encoding UTF-8
#' 
#' @examples
#' 
#' \dontrun{
#' msg = "Ceci est un test !"
#' hook = "nf71q9d5u7dwxmpygz75gpqyqr"
#' server = "https://mattermost.g-eau.fr"
#' alert_mattermost(msg, server, hook)
#' }

alert_mattermost = function (msg, server, hook, user = "nono", channel = NULL, alert = TRUE) {
    if (!is.null(channel) & !grepl("^@", channel)) {
        channel = gsub("[.]", "", channel)
    }
    json_text = paste(
        c(
            sprintf("\\\"username\\\":\\\"%s\\\"", user),
            sprintf("\\\"channel\\\":\\\"%s\\\"", channel),
            sprintf("\\\"text\\\":\\\"%s\\\"", paste(msg, collapse = "\n"))
        ),
        collapse = ", "
    )
    server_hook = sprintf("%s/hooks/%s", server, hook)

    command = sprintf(
        "curl -i -X POST -H 'Content-Type: application/json' -d \"{%s}\" %s", 
        json_text,
        server_hook
    )
    if (alert == TRUE) {
        invisible(system(command, ignore.stdout = TRUE, ignore.stderr = TRUE))
    }
    else {
        command
    }
}

