---
format:
  html:
    toc: true
    toc-location: left
    number-sections: true
    self-contained: true
  docx:
    toc: false
    toc-title: Indice
    section-numbers: true
    reference-doc: "files/template.docx"
    output-file: "manuscript"
editor_options: 
  chunk_output_type: console
execute:
  echo: false
  warning: false
crossref:
  fig-title: Figure
  fig-prefix: Figure
  tbl-title: Table
  tbl-prefix: Table
# params:
#   template: ""
#   author: ""
#   advisor: ""
#   coadvisor: ""
#   location: ""
#   date: ""
#   institution: ""
#   faculty: ""
#   program: ""
#   type: ""
#   title: ""
---

```{r}
#| label: setup

source("http://inkaverse.com/docs.r")
doc <- inti::gdoc2qmd(file = "article.zip"
                      # , type = "listfull"
                      )
params <- doc$params
```

```{r}
#| eval: true
#| results: 'asis'

if(length(params) > 0) {
 cover <- list.files(path = "files/"
                    , pattern = paste0("cover-", params$template)
                    , full.names = T) %>% 
  knitr::knit_child(quiet = TRUE) %>% 
  cat(sep = '\n')
 }
```

```{r}
#| results: 'asis'

doc$path %>% 
  knitr::knit_child(quiet = TRUE) %>% 
  cat(sep = '\n')
```

```{r}
knitr::knit_exit()
```

```{r}
#| label: pdf to jpeg
#| eval: false

library(tidyverse)
library(magick)

pdf4pub <- list.files(".", full.names = T, recursive = T
                      , pattern = "img.+.pdf") 

path <- dirname(pdf4pub)

imgs <- 1:length(pdf4pub) %>% map(\(x) {
  
  filename <- pdf4pub[x] %>% 
    basename() %>% 
    gsub(".pdf", "\\1.jpeg", .) 
  
  pdf4pub[x] %>% 
    image_read_pdf() %>% 
    # image_transparent("red") %>% 
    image_write(format = "jpeg", file.path(path, filename))
  
})
```

```{r}
#| label: Images to PDF
#| eval: false

library(tidyverse)
library(magick)
library(qpdf)

img2pdf <- list.files(".", full.names = T
                      , recursive = T
                      , pattern = "images") %>% 
  image_read() %>% 
  image_write(format = "pdf"
              , file.path(getwd(), "figures.pdf"))
```

```{r}
#| label: Images to grids
#| eval: false

library(tidyverse)
library(magick)
library(cowplot)

pdf4pub <- list.files(".", full.names = T, recursive = T
                      , pattern = "FigureX") %>% 
  image_read(., density = 600)
  
grid <- list(
  pdf4pub[1] %>% image_crop(image = ., "0x0+0+1500")
  , pdf4pub[2]
  ) %>%  
  map( ~ image_ggplot(.)) %>% 
  plot_grid(plotlist = ., labels = "auto", ncol = 2)

plot <- grid %>% 
  ggsave(plot = ., "manuscript/Figure-X.jpg"
         , units = "cm"
         , width = 20
         , height = 10
         )
```

```{r}
#| label: zip file
#| eval: false

tozip <- "manuscript" 

# unlink(paste0(tozip, ".zip"), recursive = T)

utils::zip(zipfile = paste0(tozip, ".zip")
                             , files = tozip
                             , flags = "-r9Xj"
                             )
```
