#' Format data
#'
#' Format data for other MRgrowth functions
#'
#' @param x (data frame) Input data containing one row per capture event and columns for individual ID, date/time (formatted as a Date or POSIX), and body size measurement.
#' @param id.col (character) Name of column containing unique individual IDs (default = "id")
#' @param date.col (character) Name of column containing dates/times (default = "date")
#' @param size.col (character) Name of column containing body size measurements (default = "size")
#' @param units (character) Units to be returned for time intervals between measurements. One of "hours", "days", "weeks", "years" (default = "years")
#' @param retain (character) Determines how the function should handle more than two measurements per individual. "max" returns the first and last measurement (after removing NAs), "random" = randomly selects two measurements (after removing NAs), "all" = keeps all measurements with growth intervals between measurements 1 and 2, 2 and 3, 3 and 4, etc. Note that "all" results in pseudoreplication. (default = "max")
#' @param seed (integer) Seed to use for random selections if \code{retain="random"} (default = 1701).
#'
#' @return Data frame of measurements and capture intervals formatted for MRgrowth functions. Each row is a pair of capture events and associated measurements for an individual.
#'
#' Column \code{id} = IDs as entered in the input data
#'
#' Column \code{size1} = size at capture
#'
#' Column \code{size2} = size at recapture
#'
#' Column \code{date1} = date at capture
#'
#' Column \code{date2} = date at recapture
#'
#' Column \code{td} = time difference between date1 and date2 in the units specified by the units argument.
#'
#' @details
#' It takes a long-format data frame of capture events and measurements (one row per individual per capture) and converts it into the wide-format (one row per pair of capture events per individual) needed for MRgrowth
#'
#' If \code{retain} is set to "random", only 1 pair of capture events will be retained per individual. The \code{seed} argument ensures repeatability of the code.
#'
#' \strong{Note}: Any NA data are removed as part of the function before applying the \code{retain} argument. Thus, if an individual was captured 3 times and only measured the 2nd and 3rd time, the data for the 2nd and 3rd capture events will be returned even if \code{retain="max"}
#'
#' \strong{Note}: Only individuals with at least 2 capture events (with no NAs) are returned. Any individuals that were never recaptured or did not have all data recorded for at least two recaptures are removed.
#'
#' @examples
#'
#' data(MRdata)
#'
#' #format data with years as the time units and the first and last
#' #measurement when more than 2 captures are present for an individual.
#' formatted.data <- format.data(
#'   x = MRdata,
#'   id.col = "id",
#'   date.col = "date",
#'   size.col = "size",
#'   units = "years",
#'   retain = "max"
#' )
#' @export

format.data <- function(x,id.col="id",date.col="date",size.col="size", units="years",retain="max",seed=1701){

  if(length(units) != 1 || !units %in% c("hours", "days", "weeks", "years" )){
    stop("Invalid unit. The units argument must contain one of 'hours', 'days','weeks','years'.", call. = FALSE)}

  if(length(retain) != 1 || !retain %in% c("max","random","all")){
    stop("Invalid retain. The retain argument must contain one of 'max', 'random','all'.", call. = FALSE)}


  set.seed(seed)

  data <- x

  #rename columns
  colnames(data)[which(colnames(data)==id.col)] <- "id"
  colnames(data)[which(colnames(data)==date.col)] <- "date"
  colnames(data)[which(colnames(data)==size.col)] <- "size"


  if(inherits(data$date,c("Date","POSIXt"))==FALSE){stop("date.col is not in a Date or POSIX format",call.=FALSE)}

  #subset to the columns needed for the function
  data <- data[,which(colnames(data) %in% c("id","date","size"))]

  #remove NAs
  data <- na.omit(data)

  #sort by id and date
  data <- data[with(data,order(id,date)),]

  gdata <- vector("list",length(unique(data$id)))
  for(i in 1:length(unique(data$id))){

    data.i <- data[which(data$id == unique(data$id)[i]),]

    if(nrow(data.i) > 1){ #only proceed if there is a second growth measure
      if(retain=="max"){data.i <- data.i[c(1,nrow(data.i)),]} #if retain is set to max, extract first and last data point
      if(retain=="random"){data.i <- data.i[sort(sample(1:nrow(data.i),2,replace=FALSE)),]} #if retain is set to random, randomly select two rows

      size1 <- data.i$size[1:(nrow(data.i)-1)] #extract initial sizes
      size2 <- data.i$size[2:nrow(data.i)] #extract recapture sizes
      date1 <- data.i$date[1:(nrow(data.i)-1)] #extract initial dates
      date2 <- data.i$date[2:nrow(data.i)] #extract recapture dates
      td <- as.numeric(difftime(date2,date1,units="days"))
      if(units=="hours"){td <- td*24}
      if(units=="weeks"){td <- td/7}
      if(units=="years"){td <- td/365}

      gdata[[i]] <- cbind.data.frame(id=data.i$id[1],size1,size2,date1,date2,td)
    } #close if(nrow(data.i) > 1)
  }#close for i in 1:length
  gdata <- do.call("rbind.data.frame",gdata)

  gdata
} #close format.data function
