emmeans_table_function <- function(data, var_expliquee, var_explicatives, type_comp,output,ref_index,input) {
  tryCatch({


    formule_regression <- as.formula(paste0(var_expliquee, "~", paste(var_explicatives, collapse = "*")))

    # Ajuster le modèle de régression linéaire
    mod <- lm(formule_regression, data = data)


    # Créer les formules
    if (type_comp == 'trt.vs.ctrl') {
      structure_formule = as.formula(paste0("trt.vs.ctrl~",paste(var_explicatives,collapse = "*")))
      emm <- emmeans(mod, structure_formule)$emmeans
    } else if (type_comp == 'pairwise') {
      structure_formule = as.formula(paste0("pairwise~",paste(var_explicatives,collapse = "*")))
      emm <- emmeans(mod, structure_formule)$emmeans
    } else if (type_comp == 'personnalisé') {
      structure_formule = as.formula(paste0("~",paste(var_explicatives,collapse = "*")))
      emm <- emmeans(mod, specs=var_explicatives)
    }  
    # Convertir en tableau de données et arrondir
    emmeans_table <- as.data.frame(emm)
    
    for (col in names(emmeans_table)) {
      if (is.numeric(emmeans_table[[col]])) {
        emmeans_table[[col]] <- round(emmeans_table[[col]], 3)
      }
    }
    
    emmeans_table <- na.omit(emmeans_table)
    output$graph_compared_mean <- renderPlotly({
      return(comparisonGraph(emmeansObj = emm))
    })
    output$emmeans_result <- renderPrint({
      return(emm)
    })
    return(emmeans_table)
    
  }, warning = function(w) {
    warning("Avertissement rencontré : ", conditionMessage(w))
    return(NULL)
  }, error = function(e) {
    message("Erreur rencontrée : ", conditionMessage(e))
    return(NULL)
  })
}

emmeans_function <- function(data, var_expliquee, var_explicatives) {
  tryCatch({
    # Construction de la formule de régression
    formule_regression <- as.formula(paste0(var_expliquee, "~", paste(var_explicatives, collapse = "*")))
    
    # Ajuster le modèle de régression linéaire
    mod <- lm(formule_regression, data = data)
    

    # Calculer les moyennes marginales estimées (emmeans)
    emm <- emmeans(mod, specs = var_explicatives)
    
    return(emm)
    
  }, warning = function(w) {
    warning("Avertissement rencontré : ", conditionMessage(w))
    return(NULL)
  }, error = function(e) {
    message("Erreur : ", conditionMessage(e))
    return(NULL)
  })
}


contrasts_table_function <- function(data, var_expliquee, var_explicatives, type_comp, output,input,ref_index,contrast_list) {
  tryCatch({
    # Créer les formules
    structure_formule <- as.formula(paste0("~",paste(var_explicatives,collapse = "*")))
    formule_regression <- as.formula(paste0(paste0(var_expliquee,"~"),paste(var_explicatives,collapse = "*")))
    
    # Ajuster le modèle de régression linéaire
    mod <- lm(formule_regression, data = data)
    
    # Calculer les moyennes marginales estimées (emmeans)
    emm <- emmeans(mod, structure_formule)
    
    # Calculer les contrastes
    if (type_comp == 'trt.vs.ctrl') {
        contr <- contrast(emm, type_comp, ref = ref_index)
    } else if (type_comp == "pairwise") {
        contr <- contrast(emm, type_comp)
    } else if (type_comp == "personnalisé") {
      list_contrasts <- contrast_list
      contr <- contrast(emm, method=list_contrasts)
    }
    
    # Convertir en tableau de données et arrondir
    emmeans_table <- as.data.frame(contr)
    
    for (col in names(emmeans_table)) {
      if (is.numeric(emmeans_table[[col]])) {
        emmeans_table[[col]] <- round(emmeans_table[[col]], 3)
      }
    }
    
    emmeans_table <- na.omit(emmeans_table)
    return(emmeans_table)
    
  }, warning = function(w) {
    warning("Avertissement rencontré : ", conditionMessage(w))
    return(NULL)
  }, error = function(e) {
    message("Erreur rencontrée : ", conditionMessage(e))
    return(NULL)
  })
}


ref_index_function <- function(emm,input,Temoins){
  tryCatch({
    t = ""
    for (col in names(Temoins)) {
      t <- paste(t,input[[paste0("temoin_", col)]],collapse = " ")
    }
    t <- substr(t,2,nchar(t))
    row_concat <- apply(emm@grid[,-ncol(emm@grid)], 1, function(row) {
      paste(row, collapse = " ")
    })
    ind <- which(row_concat == t)
    return(ind)
  },
  error = function(e) {
    message('An Error Occurred')
    cat("Erreur :", conditionMessage(e), "\n")
    traceback()
    return(NULL)
  },
  warning = function(w) {
    message('A Warning Occured')
    print(w)
    formula <- formula(paste(num_column, "~", cat))
    a <- leveneTest(formula, data = merged_data)
    return(a)
  })
  
}

contrast_list_function <- function(emm) {
  ref_list <- apply(emm@grid[,-ncol(emm@grid)], 1, function(row) {
      paste(row, collapse = " ")
    })

    return(ref_list)
}

contrast_function <- function(input,output,emm,ref1,ref2,data){

  tryCatch({
    # On doit d'abord recréé l'objet emmeans
      var_expliquee=input$emmeans_expliquees
      var_explicatives=input$emmeans_explicatives
      emm <- emmeans_function(data,var_expliquee,var_explicatives)

      #On réccupère ensuite les différents niveaux possibles
      ref_list <- contrast_list_function(emm)

      #On initialise nos vecteurs
      contrast1 <- rep(0,length(ref_list))
      contrast2 <- rep(0,length(ref_list))
      for (ref in ref1) {
        ind <- which(ref_list == ref)
        contrast1[ind] = 1
      }
      for (ref in ref2) {
        ind <- which(ref_list == ref)
        contrast2[ind] = -1
      }
      cont <- contrast1+contrast2
      return(cont)
  },
  error = function(e) {
    message('An Error Occurred')
    cat("Erreur :", conditionMessage(e), "\n")
    traceback()
    return(NULL)
  },
  warning = function(w) {
    message('A Warning Occured')
    print(w)
    return(a)
  })

  
}