```{r "{{method_name}}_cor_miRNA_config", include = FALSE, warnig = FALSE}
# ###########################################
# ################# READ ME #################
# ###########################################
#
# This template assumes that the following variables exists
# => current_organism_info$Bioconductor_DB[1] :: organism database to translate genes
# => method :: method object
# => method_name :: method name
  
method <- "{{method_name}}"
outdir <- file.path(output_files, method)
check_and_create_dir(outdir)
strat_pairs <- as.data.frame(all_pairs)
strat_pairs <- strat_pairs[, "{{method_name}}"]
strat_data <- all_pairs[strat_pairs,]
strat_data$miRNA_names <- mirna_names[match(strat_data$miRNAseq, mirna_names$ACCESSION), "NAME"]
strat_data <- merge(strat_data, gene_id_translation, by.x = "RNAseq", by.y = "ensembl_gene_id", all.x = TRUE)

# q()
strat_data <- as.data.frame(strat_data)
data.table::setnames(strat_data, paste0(method, "_correlation"), "Correlation")
selected_cols <- c("miRNA_names", "miRNAseq","Symbol","RNAseq", "predicted", "validated", "multimir","pred_and_val","predicted_c", "validated_c","entrezgene", "Correlation")
strat_data <- strat_data[,selected_cols]

strat_data_table <- strat_data[,c("miRNA_names", "miRNAseq","Symbol","RNAseq", "predicted_c", "validated_c","entrezgene", "Correlation")]


DH_results_genes <- match(strat_data_table$RNAseq, RNAseq$DH_results$gene_name)
DH_results_miRNA <- match(strat_data_table$miRNAseq, miRNAseq$DH_results$gene_name)

strat_data_table$DEG_tag_target <- RNAseq$DH_results[DH_results_genes, "genes_tag"]
strat_data_table$Target_log2FC <- RNAseq$DH_results$mean_logFCs[DH_results_genes]

strat_data_table$DEM_tag_miRNA <- miRNAseq$DH_results[DH_results_miRNA, "genes_tag"]
strat_data_table$miRNA_log2FC <- miRNAseq$DH_results$mean_logFCs[DH_results_miRNA]



DH_results_miRNAs <- match(strat_data_table$miRNAseq, miRNAseq$DH_results$gene_name)
approach <- unlist(strsplit(method, "_RNA_vs_miRNA_"))
if (approach[2] != "normalized_counts") {

  strat_data_table$miRNA_mod <- miRNAseq$DH_results[DH_results_miRNAs, "Cluster_ID"]    
  strat_data_table$miRNA_MM <- miRNAseq$DH_results[DH_results_miRNAs, "Cluster_MM"]  

}
if (approach[1] != "normalized_counts") {
  
  strat_data_table$RNA_mod <- RNAseq$DH_results[DH_results_genes, "Cluster_ID"]    
  strat_data_table$RNA_MM <- RNAseq$DH_results[DH_results_genes, "Cluster_MM"]  

}

strat_data_table2 <- strat_data_table
data.table::setnames(strat_data_table, 
  c("miRNA_names", "miRNAseq", "Symbol",       "RNAseq",   "predicted_c",       "validated_c",       "entrezgene"),
  c("miRNA",       "miRNA_ID", "Symbol_target","Target_ID","Predicted_DB_count","Validated_DB_count","ENTREZGENE_target"))


```



```{r "{{method_name}}_cor_miRNA_table", echo = FALSE, message=FALSE, warning=FALSE, results = "asis"}
if (nrow(strat_data_table) > 20000){
  cat(paste0("\n\nThis strategy finds too many significant pairs. Please check ", method, "/target_results_table.txt. \n\n"))

} else {
  DT::datatable(strat_data_table, filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
        options = list(
          paging = TRUE,
          colReorder = TRUE,
          dom = 'lftBip',
          buttons = c('copy', 'csv', 'excel')
    ))
}
# strat_data <- data.frame()
```


```{r "{{method_name}}_cor_miRNA_table_error", eval = FALSE, results='asis', echo = FALSE, message=FALSE, warning=FALSE}

cat("This method was launched but no significant miRNA-target gene relations were found in multiMiR.\n")

```



```{r "{{method_name}}_dem_summary_config", echo = FALSE, message=FALSE, warning=FALSE}

all_miRNA_summary <- data.frame( stringsAsFactors = FALSE)
for (mirna_name in unique(paste0(strat_data$miRNA_names, "_",strat_data$miRNAseq))) {
   mirna_name <- unlist(strsplit(mirna_name, "_"))
   mirna <- mirna_name[1]
   mirna_id <- mirna_name[2]
   mirna_info <- strat_data[strat_data$miRNAseq == mirna_id, ]

   
   dem_summary <- data.frame(stringsAsFactors = FALSE,
               miRNA = mirna,
               miRNA_ID = mirna_id,
               Significant_targets = length(unique(mirna_info$RNAseq)),
               Targets_in_multiMiR = length(unique(mirna_info$RNAseq[mirna_info$multimir])),
               Predicted_targets = length(unique(mirna_info$RNAseq[mirna_info$predicted])),
               Validated_targets = length(unique(mirna_info$RNAseq[mirna_info$validated]))
               )
  
   all_miRNA_summary <- rbind(all_miRNA_summary, dem_summary)
}
```

```{r "{{method_name}}_dem_summary_text", echo = FALSE,  results='asis',message=FALSE, warning=FALSE}

cat("### Strategy miRNAs summary\n\n")

```

```{r "{{method_name}}_dem_summary", echo = FALSE, message=FALSE, warning=FALSE}

DT::datatable(all_miRNA_summary, filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
      options = list(          paging = TRUE,
        paging = TRUE,
        colReorder = TRUE,
        dom = 'lftBip',
        buttons = c('copy', 'csv', 'excel')
    ))

```

```{r "{{method_name}}_specific_overlapping_config", echo = FALSE, message=FALSE, warning=FALSE, eval = specific_evaluation}

specific_ct <- miRNA_cont_tables_adj[miRNA_cont_tables_adj$strategy == "{{method_name}}",]
splitted_c_tables <- split(specific_ct, specific_ct$db_group)
stats_table <- list()
for(db_group in c("predicted", "validated")){
  filtered_cont <- splitted_c_tables[[db_group]]

  cat(paste0("\n\n### Dotplot of miRNA Odds ratio and Fisher's exact test P value for ", db_group, " pairs databases\n\n\n"))

 filtered_cont$FDR <- filtered_cont$p.adjust

  overal_OR <- plot_odds_ratio(filtered_cont, 
                                OR_col = "Odds_ratio",
                                pval_col = "FDR",
                                y_col = "miRNA",
                                text_col = "FDR")
  plot(overal_OR)

  cat("\n\n")
  stats_table[[db_group]] <- filtered_cont[,c("miRNA", "Pvalue","FDR", "Odds_ratio")]
  # stats_table[[db_group]]$FDR <- filtered_cont$p.adjust

cat("\n\n")
}


```

```{r "{{method_name}}_specific_overlapping_pred_text", echo = FALSE,  results='asis', message=FALSE, warning=FALSE, eval = specific_evaluation}

  cat("\n\n### Table of miRNA Odds ratio and Fisher's exact test P value for predicted pairs databases\n\n")
```

```{r "{{method_name}}_specific_overlapping_pred_table", echo = FALSE, message=FALSE, warning=FALSE, eval = specific_evaluation}

  DT::datatable(stats_table[["predicted"]], filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
      options = list(          paging = TRUE,
        paging = TRUE,
        colReorder = TRUE,
        dom = 'lftBip',
        buttons = c('copy', 'csv', 'excel')
    ))
``` 

```{r "{{method_name}}_specific_overlapping_val_text", echo = FALSE,  results='asis', message=FALSE, warning=FALSE, eval = specific_evaluation}

  cat("\n\n### Table of miRNA Odds ratio and Fisher's exact test P value for validated pairs databases\n\n")
```

```{r "{{method_name}}_specific_overlapping_val_table", echo = FALSE, message=FALSE, warning=FALSE, eval = specific_evaluation}

  DT::datatable(stats_table[["validated"]], filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
      options = list(          paging = TRUE,
        paging = TRUE,
        colReorder = TRUE,
        dom = 'lftBip',
        buttons = c('copy', 'csv', 'excel')
    ))
``` 


```{r "{{method_name}}_dem_modules", echo = FALSE, message = FALSE, warning = FALSE, eval = approach[1] %in% c("Eigengene", "hub_1")}
"%>%" <- magrittr::"%>%"

all_miRNA_mod_summary <- strat_data_table %>% 
                            dplyr::group_by(miRNA, miRNA_ID, RNA_mod) %>% 
                            dplyr::summarise(Significant_targets = length(Target_ID), 
                                      Targets_in_multiMiR = sum(Predicted_DB_count > 0 | Validated_DB_count > 0), 
                                      Predicted_targets = sum(Predicted_DB_count > 0), 
                                      Validated_targets = sum(Validated_DB_count > 0))

all_miRNA_mod_summary <- as.data.frame(all_miRNA_mod_summary)

all_miRNA_mod_summary$Pred_percentage <- all_miRNA_mod_summary$Predicted_targets / all_miRNA_mod_summary$Significant_targets
all_miRNA_mod_summary$Val_percentage <- all_miRNA_mod_summary$Validated_targets / all_miRNA_mod_summary$Significant_targets
# save(all_miRNA_mod_summary, strat_data_table, file = "/mnt/scratch/users/bio_267_uma/josecordoba/NGS_projects/LaforaRNAseq/target_miRNA_wf/miRNA_RNAseq_analysis.R_0002/test_mod.RData")
# q()



utils::write.table(all_miRNA_mod_summary, file = file.path(outdir, "all_miRNA_mod_summary.txt"), quote=FALSE, col.names=TRUE, row.names = FALSE, sep="\t")

DT::datatable(all_miRNA_mod_summary, filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
      options = list(          paging = TRUE,
        paging = TRUE,
        colReorder = TRUE,
        dom = 'lftBip',
        buttons = c('copy', 'csv', 'excel')
    ))




```

```{r "{{method_name}}_dem_table_config", echo = FALSE, message=FALSE, warning=FALSE}

library(plyr)

save(strat_data_table2, file = file.path(outdir, "test.RData"))
if (output_pairs == "validated"){
  strat_data_table2 <- strat_data_table2[strat_data_table2$Validated_DB_count > 0,]
} else if ( output_pairs == "multimir"){
  save(strat_data_table2,file = file.path(outdir, "strat_data_table2.RData") )
    strat_data_table2 <- strat_data_table2[strat_data_table2$Validated_DB_count > 0 | strat_data_table2$Predicted_DB_count > 0,]
} 


utils::write.table(strat_data_table2, file = file.path(outdir, "target_results_table.txt"), quote=FALSE, col.names=TRUE, row.names = FALSE, sep="\t")
  

data_for_clusters_to_enrichments <-  plyr::ddply(strat_data_table2, .(miRNA), summarise, genes = list(Target_ID))
data_for_clusters_to_enrichments$genes <- unlist(lapply(data_for_clusters_to_enrichments$genes, function(gene_set){paste(gene_set, collapse = ",")}))
utils::write.table(data_for_clusters_to_enrichments, col.names = FALSE, row.names = FALSE, quote = FALSE, sep = "\t", file =  file.path(outdir, "miRNA_to_enrich.txt"))
gene_attributes <- strat_data_table2[,c("miRNA","Target_ID", mapping_output)]
colnames(gene_attributes) <- c("cluster", "geneid", mapping_output)
utils::write.table(unique(gene_attributes), file = file.path(outdir, "gene_attributes.txt"), quote=FALSE, col.names=TRUE, row.names = FALSE, sep="\t")

utils::write.table(all_miRNA_summary, file = file.path(outdir, "all_miRNA_summary.txt"), quote=FALSE, col.names=TRUE, row.names = FALSE, sep="\t")

```



