---
title: "Generate QC Report"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Generate QC Report}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Import example metabolomics data

```{r render}
library(metaboprep)

# import data directly as a Metaboprep object
mydata <- read_metabolon(system.file("extdata", "metabolon_v1.1_example.xlsx", package = "metaboprep"), 
                         sheet="OrigScale",
                         return_Metaboprep = TRUE)

```


## Identify the Xenobiotics to exclude from the QC steps

```{r xeno_identification}
xenos <- mydata@features[mydata@features$pathway == "xenobiotic", "feature_id"]

## how many xenobiotics identified
length(xenos)
```

## QC the example Metabolon data


```{r qc}
mydata <- mydata |>
  quality_control(source_layer        = "input", 
                  sample_missingness  = 0.2, 
                  feature_missingness = 0.2, 
                  total_peak_area_sd  = 5, 
                  outlier_udist       = 5, 
                  outlier_treatment   = "leave_be", 
                  winsorize_quantile  = 1.0, 
                  tree_cut_height     = 0.5, 
                  pc_outlier_sd       = 5,
                  feature_selection   = "least_missingness", 
                  features_exclude_but_keep = xenos 
                  )

```

## Generate the metaboprep report

```{r}
# render report
generate_report(mydata,
                project         = "myproject",
                output_dir      = getwd(),
                output_filename = NULL,
                format          = "html",
                template        = "qc_report")
```


```{r, echo=FALSE}
file.copy(file.path(getwd(), "myproject_metaboprep_qc_report.html"), 
          file.path(getwd(), "../docs/articles/myproject_metaboprep_qc_report.html"), overwrite = TRUE)
```

```{r, echo=FALSE, results="asis"}
cat('
<div id="iframe-container" style="width: 100%;">
  <iframe id="myIframe" src="https://mrcieu.github.io/metaboprep/articles/myproject_metaboprep_qc_report.html" 
          width="100%" style="border: none;"></iframe>
</div>

<script>
  function resizeIframe() {
    var iframe = document.getElementById("myIframe");
    if (iframe) {
      iframe.style.height = iframe.contentWindow.document.body.scrollHeight + "px";
    }
  }

  document.getElementById("myIframe").onload = function() {
    setTimeout(resizeIframe, 500);
  };
</script>
')
```
