#' (internal)
#' @noRd
#' @noRd
mstep_rjmcmc_update <- function(X,
                              muBar,
                              p,
                              thetaYList,
                              ZOneDim,
                              hparam,
                              hparamInit,
                              qVec,
                              qnew,
                              dVec,
                              sVec,
                              constraint,
                              clusInd,
                              mVec,
                              Mind) {


  # print("mStep")
  ## rjmcmc for m

  m <- sum(clusInd)
  n <- ncol(X)
  # empty cluster
  emptyZ <- setdiff(which(clusInd == 1), ZOneDim)

  currentStep <- c()

  ## birth and death
  if (Mind == "BD") {
    if (length(emptyZ) > 1) {
      currentStep <- c("death")
    }
    else if (m == mVec[1] | length(unique(ZOneDim)) == 1) {
      currentStep <- c("birth")
    }
    else if (m == mVec[2]) {
      if (length(emptyZ) > 0) {
        currentStep <- c("death")
      } else {
        currentStep <- c("NA")
      }
    } else {
      if (length(emptyZ) > 0) {
        currentStep <- c("birth", "death")
      } else {
        currentStep <- c("birth")
      }
    }
  }

  if (Mind == "SC") {
    if (m == mVec[1] | length(unique(ZOneDim)) == 1) {
      currentStep <- c("split")
    } else if (m == mVec[2]) {
      currentStep <- c("combine")
    } else {
      currentStep <- c("combine", "split")
    }
  }


  indChar <- sample(currentStep, 1)
  # cat("======",indChar, "======>\n")

  if (indChar == "birth") {
    birthInd <- which(clusInd == 0)[1]

    newClusterThetaY <- generate_new_cluster_parameters(m, n, p, hparam, muBar, qnew, thetaYList, constraint, clusInd)

    ## adjust tao in the combine
    combinedThetaList <- combine_cluster_parameters(thetaYList, newClusterThetaY, birthInd)
    jacobianAdj <- m * log(1 - newClusterThetaY@tao)

    ## adjust q
    qVecNew <- qVec
    qVecNew[birthInd] <- qnew


    ## adjust clusInd
    clusIndNew <- clusInd
    clusIndNew[birthInd] <- 1


    oldDensity <- likelihood(thetaYList, ZOneDim, qVec, muBar, X) + evaluate_prior(m, p, muBar, hparam, thetaYList, ZOneDim, qVec, constraint, clusInd)
    newDensity <- likelihood(combinedThetaList, ZOneDim, qVecNew, muBar, X) + evaluate_prior(m + 1, p, muBar, hparam, combinedThetaList, ZOneDim, qVecNew, constraint, clusIndNew)

    newClusterThetaYEval <- evaluate_new_cluster_parameters(m, p, hparam, muBar, qnew, thetaYList, newClusterThetaY, constraint)

    emptyZ <- setdiff(which(clusIndNew == 1), ZOneDim)

    numeratorAlpha <- newDensity + jacobianAdj
    denominatorAlpha <- oldDensity + newClusterThetaYEval + log(length(emptyZ))

    probAlpha <- calculate_ratio_cpp(numeratorAlpha, denominatorAlpha)
    acceptP <- min(1, probAlpha)

    res <- rbinom(1, size = 1, prob = acceptP)
    # cat("birth prob = ", probAlpha, "====>\n")


    if (res == 1) {
      ## birth
      # print("birth succeed=====>")
      # cat("birth prob = ", probAlpha, "====>\n")

      thetaYList <- combinedThetaList
      qVec <- qVecNew
      clusInd <- clusIndNew
      thetaYList <- clear_inactive_components(thetaYList, clusInd, mVec[2])
    } else {
      ## stay
      # print("birth reject =====>")
    }
  }
  else if (indChar == "death") {
    ## no update

    emptyZ <- setdiff(which(clusInd == 1), ZOneDim)
    chooseZprob <- 0
    if (length(emptyZ) == 1) {
      deathInd <- emptyZ
    } else {
      deathInd <- sample(x = emptyZ, size = 1)
      chooseZprob <- log(1 / length(emptyZ))
    }

    ## adj qVec and clusInd
    qVecNew <- qVec
    clusIndNew <- clusInd
    qVecNew[deathInd] <- 0
    clusIndNew[deathInd] <- 0


    dropCluster <- subset_theta_y(thetaYList, deathInd)

    ## adjust tao

    leftThetaY <- remove_theta_y_component(thetaYList, deathInd)
    dropClusterDval <- evaluate_new_cluster_parameters(m - 1, p, hparam, muBar, qnew, leftThetaY, dropCluster, constraint)

    jacobianAdj <- (m - 1) * log(1 - dropCluster@tao)


    oldDensity <- evaluate_prior(m, p, muBar, hparam, thetaYList, ZOneDim, qVec, constraint, clusInd)
    newDensity <- evaluate_prior(m - 1, p, muBar, hparam, leftThetaY, ZOneDim, qVecNew, constraint, clusIndNew)


    numeratorAlpha <- newDensity + dropClusterDval + chooseZprob
    denominatorAlpha <- oldDensity + jacobianAdj

    # cat("diff  = ", numeratorAlpha - denominatorAlpha, "=====> \n" )

    probAlpha <- calculate_ratio_cpp(numeratorAlpha, denominatorAlpha)
    acceptP <- min(1, probAlpha)

    res <- rbinom(1, size = 1, prob = acceptP)

    if (res == 1) {
      ## contract
      # print("death succeed=====>")
      # cat("death prob = ", probAlpha, "====>\n")

      # stop("=====>")

      thetaYList <- leftThetaY
      qVec <- qVecNew
      clusInd <- clusIndNew
      thetaYList <- clear_inactive_components(thetaYList, clusInd, mVec[2])
    } else {
      # print("death stay =====>")
    }
  }

  else if (indChar == "combine") {
    ## choose two  positions to combine
    combineClusInd <- sample(x = sort(unique(ZOneDim)), size = 2, prob = 1 / table(ZOneDim))

    logProbCombineZ <- log(1 / choose(length(unique(ZOneDim)), 2))

    clusIndNew <- clusInd
    qVecNew <- qVec
    clusIndNew[combineClusInd] <- 0
    qVecNew[combineClusInd] <- 0

    ## choose one position to fill combined clus
    combinedClusInd <- which(clusIndNew == 0)[1]
    clusIndNew[combinedClusInd] <- 1
    qVecNew[combinedClusInd] <- qnew

    ## propose values for new clusters
    combinedThetaYList <- propose_combined_clusters(X, thetaYList, hparam, combineClusInd, combinedClusInd, qVecNew, constraint)
    combinedThetaYList <- clear_inactive_components(combinedThetaYList, clusIndNew, mVec[2])
    combineEval <- evaluate_combined_clusters(X, combinedThetaYList, hparam, combinedClusInd, qVecNew, constraint)
    ## evaluate values for old cluster
    splitEval <- evaluate_split_clusters(X, combinedThetaYList, thetaYList, hparam, combinedClusInd, combineClusInd, qVec, constraint)


    ## calculate Jacobian

    JacEval <- calculate_jacobian(p, combinedThetaYList, thetaYList, combinedClusInd, combineClusInd)


    ## combine Z

    ZOneDimNew <- combine_allocations(ZOneDim, combineClusInd, combinedClusInd)

    ## eval split

    evalZProb <- evaluate_split_allocations(X, ZOneDimNew, ZOneDim, thetaYList, combinedClusInd, combineClusInd)

    # update Y
    combinedThetaYList@Y <- update_latent_scores(X, combinedThetaYList, ZOneDimNew, clusIndNew, qVecNew)



    combinedThetaYListTEST <- combinedThetaYList
    ZOneDimNewTEST <- ZOneDimNew
    for (i in 1:5) {
      MCMCobj <- stay_mcmc_update(X, combinedThetaYListTEST, ZOneDimNewTEST, hparam, qVecNew, qnew, dVec, sVec, constraint, clusIndNew)
      ZOneDimNewTEST <- MCMCobj$ZOneDim
      combinedThetaYListTEST <- MCMCobj$thetaYList
      # hparam = MCMCobj$hparam
    }


    oldDensity <- likelihood(thetaYList, ZOneDim, qVec, muBar, X) + evaluate_prior(m, p, muBar, hparam, thetaYList, ZOneDim, qVec, constraint, clusInd)
    newDensity <- likelihood(combinedThetaYListTEST, ZOneDimNewTEST, qVecNew, muBar, X) + evaluate_prior(m - 1, p, muBar, hparam, combinedThetaYListTEST, ZOneDimNewTEST, qVecNew, constraint, clusIndNew)

    numer <- newDensity + splitEval + JacEval
    denom <- oldDensity + combineEval + logProbCombineZ

    # cat("combine diff = ", newDensity - oldDensity, "====>\n")
    # cat("combine diff = ", numer - denom, "====>\n")

    probAlpha <- calculate_ratio_cpp(numer, denom)
    acceptP <- min(1, probAlpha)
    res <- rbinom(1, size = 1, prob = acceptP)

    if (res == 1) {
      # print("combine success=====>")

      thetaYList <- combinedThetaYListTEST
      ZOneDim <- ZOneDimNewTEST
      clusInd <- clusIndNew
      qVec <- qVecNew
      thetaYList <- clear_inactive_components(thetaYList, clusInd, mVec[2])
    } else {
      # print("combine fail=====>")
    }
  }

  else if (indChar == "split") {
    ## choose one existing position to split
    if (length(unique(ZOneDim)) == 1) {
      splitClusInd <- unique(ZOneDim)
    } else {
      splitClusInd <- sample(sort(unique(ZOneDim)), size = 1, prob = table(ZOneDim))
    }
    logProbSplitZ <- log(1 / length(unique(ZOneDim)))

    clusIndNew <- clusInd
    qVecNew <- qVec
    clusIndNew[splitClusInd] <- 0
    qVecNew[splitClusInd] <- 0
    ## choose two positions to fill the two clusters
    splitedClusInd <- which(clusIndNew == 0)[1:2]
    clusIndNew[splitedClusInd] <- 1
    qVecNew[splitedClusInd] <- qnew
    ## propose values for new clusters

    splitedThetaYList <- propose_split_clusters(X, thetaYList, hparam, splitClusInd, splitedClusInd, qVecNew, constraint)
    splitEval <- evaluate_split_clusters(X, thetaYList, splitedThetaYList, hparam, splitClusInd, splitedClusInd, qVecNew, constraint)

    ## calculate Jacobian

    JacEval <- calculate_jacobian(p, thetaYList, splitedThetaYList, splitClusInd, splitedClusInd)

    ## evaluate values for old cluster
    combineEval <- evaluate_combined_clusters(X, thetaYList, hparam, splitClusInd, qVec, constraint)

    ## split Z

    splitZObj <- split_allocations(X, ZOneDim, splitedThetaYList, splitClusInd, splitedClusInd)

    ZOneDimNew <- splitZObj$ZOneDim
    evalZProb <- splitZObj$evalProb

    # update Y
    splitedThetaYList@Y <- update_latent_scores(X, splitedThetaYList, ZOneDimNew, clusIndNew, qVecNew)

    splitedThetaYListTEST <- splitedThetaYList
    ZOneDimNewTEST <- ZOneDimNew
    for (i in 1:5) {
      MCMCobj <- stay_mcmc_update(X, splitedThetaYListTEST, ZOneDimNewTEST, hparam, qVecNew, qnew, dVec, sVec, constraint, clusIndNew)
      ZOneDimNewTEST <- MCMCobj$ZOneDim
      splitedThetaYListTEST <- MCMCobj$thetaYList
    }

    ## calculate acceptancy propability

    oldDensity <- likelihood(thetaYList, ZOneDim, qVec, muBar, X) + evaluate_prior(m, p, muBar, hparam, thetaYList, ZOneDim, qVec, constraint, clusInd)
    newDensity <- likelihood(splitedThetaYListTEST, ZOneDimNewTEST, qVecNew, muBar, X) + evaluate_prior(m + 1, p, muBar, hparam, splitedThetaYListTEST, ZOneDimNewTEST, qVecNew, constraint, clusIndNew)

    numer <- newDensity + combineEval
    denom <- oldDensity + splitEval + logProbSplitZ + JacEval

    # cat("diff  = ", numer - denom, "====>\n")
    probAlpha <- calculate_ratio_cpp(numer, denom)
    acceptP <- min(1, probAlpha)
    res <- rbinom(1, size = 1, prob = acceptP)

    if (res == 1) {
      # print("split success=====>")
      # cat("split prob = ", probAlpha, "====>\n")


      thetaYList <- splitedThetaYListTEST
      ZOneDim <- ZOneDimNewTEST
      clusInd <- clusIndNew
      qVec <- qVecNew
      thetaYList <- clear_inactive_components(thetaYList, clusInd, mVec[2])
    } else {
      # print("split fail=====>")
    }
  }

  return(list(thetaYList = thetaYList, ZOneDim = ZOneDim, hparam = hparam, qVec = qVec, clusInd = clusInd))
}

utils::globalVariables(c(
  "mVec", "generate_new_cluster_parameters", "evaluate_new_cluster_parameters",
  "propose_combined_clusters", "evaluate_combined_clusters",
  "evaluate_split_clusters", "calculate_jacobian",
  "combine_allocations", "evaluate_split_allocations", "update_latent_scores",
  "propose_split_clusters", "split_allocations", "res"
))
