# rLttcmprsk is the simulation method using marginal distribution and compare X_1 and X_2
rLttcmprsk <- function(cmprsk, n=1, condition=TRUE, sortu=FALSE){
  # condition is used to ensure failure numer of each failure cause must be greater than zero.
  xcmp <- rLttcmprsk0(n=n, cmprsk=cmprsk, sortu=sortu)
  if(n>1){
    if(condition){
      s <- 0
      while(length(unique(xcmp$delta))<length(cmprsk$margins)){
        stopifnot(s <= 100)
        xcmp <- rLttcmprsk0(n=n, cmprsk=cmprsk, sortu=sortu)
        s <- s + 1
      }
    }
  }
  list(xcmp=xcmp,
       cmprsk=cmprsk,
       n=n)
}
rLttcmprsk0 <- function(cmprsk, n=1, sortu=FALSE){
  margs.para.list <- cmprsk$margs.para.list
  rdist.list <- lapply(paste0("r", cmprsk$margins), get)
  xcmp0 <- matrix(0, nrow=n, ncol=length(margs.para.list))
  for(i in 1:length(rdist.list)){
    rdist <- rdist.list[[i]]
    para.pcall <- margs.para.list[[i]]
    para.pcall$n <- n
    xcmp0[,i] <- do.call(rdist, para.pcall)
  }
  tmin <- apply(xcmp0, 1, min)
  delta <- apply(xcmp0, 1, which.min)
  if(sortu){
    delta <- delta[order(tmin)]
    tmin <- sort(tmin)
  }
  data.frame(tmin=tmin, delta=delta)
}


rLttcmprsk.csh <- function(n, cmprsk, u=NULL, TinvFun=c("Reliability", "Distribution")){
  if(is.null(u)){
    if(TinvFun=="Reliability"){
      u <- sort(runif(n), decreasing = TRUE)
      xs <- sapply(u, function(x) nleqslv::nleqslv(0.2, Rxcmpf, u=x, cmprsk=cmprsk)$x)
    }
    if(TinvFun=="Distribution"){
      u <- sort(runif(n))
      xs <- sapply(u, function(x) nleqslv::nleqslv(0.2, Fxcmpf,  u=x, cmprsk=cmprsk)$x)
    }
  } else{
    if(TinvFun=="Reliability"){
      u <- sort(u, decreasing = TRUE)
      xs <- sapply(u, function(x) nleqslv::nleqslv(0.2, Rxcmpf,  u=x, cmprsk=cmprsk)$x)
    }
    if(TinvFun=="Distribution"){
      u <- sort(u)
      xs <- sapply(u, function(x) nleqslv::nleqslv(0.2, Fxcmpf,  u=x, cmprsk=cmprsk)$x)
    }
  }
  htval <- Lttcmprsk_Prob(xcmp=xs, cmprsk = cmprsk)$marg.prob$htval
  htprob <- sapply(1:length(cmprsk$margins),
                   function(x) htval[,x]/apply(htval,1,sum))
  delta <- delta0 <- rbinom(nrow(htprob), size=1, prob=htprob)
  while(length(unique(delta)) < length(cmprsk$margins)){
    delta <- delta0 <- rbinom(nrow(htprob), size=1, prob=htprob)
  }
  delta[which(delta0==0, arr.ind = TRUE)] <- 2
  xcmp <- data.frame(tmin=xs, delta=delta)
  xcmp
}

