

#' @title Get the error message of a try-error object
#' @description Get the error message of a try-error object
#' @param x an object
#' @param ... not used
#' @export
#' @return a character string with the error message or an empty character string
#' @examples 
#' x <- try(log("a"))
#' error_message(x)
#' x <- try(log(10))
#' error_message(x)
error_message <- function(x, ...){
  UseMethod("error_message")
}

#' @export
#' @describeIn error_message Default functionality
error_message.default <- function(x, ...){
  if(inherits(x, "try-error")){
    as.character(attributes(x)$condition)
  }else{
    character()  
  }
  
}


txt_recode <- function (x, from = c(), to = c()) {
  stopifnot(length(from) == length(to))
  nongiven <- unique(x[!is.na(x)])
  nongiven <- setdiff(nongiven, from)
  if (length(nongiven) > 0) {
    from <- append(x = from, values = nongiven)
    to <- append(x = to, values = nongiven)
  }
  to[match(x, from)]
}



sundayofweek <- function(x){
  xweekday <- as.integer(format(x, "%w"))
  idx <- which(xweekday != 0)
  x[idx] <- x[idx] + (7 - xweekday[idx])
  x
}

mondayofweek <- function(x){
  sundayofweek(x) - 6
}

startofmonth <- function(x){	
  x - as.integer(format(x, "%d")) + 1 
}
