---
title: "Country Population Evolution (source OWID)"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{r global, include=FALSE}
library(MASS)
library(highcharter)
library(fpp3)
library(RColorBrewer)
library(openxlsx)  
library(leaflet)
library(plotly)
library(ggplot2)
library(tidyverse)
```
Añadir
```{r}
# asociamos funciones a determinadas librerías para evitar posibles errores 
select <- dplyr::select
mutate <- dplyr::mutate
filter <- dplyr::filter
group_by <- dplyr::group_by
summarise <- dplyr::summarise
selectInput <- shiny::selectInput
```

```{r,message=FALSE,echo=FALSE}
owid_population <- read_csv('https://ctim.es/AEDV/data/owid_population.csv')  |>
  as_tibble()
```

[comment 02b]: # Función auxiliar que dibuja el gráfico de evolución de población de un país, reutilizada en los 4 renderHighchart de las columnas 2 y 3

```{r}
dibujar_poblacion <- function(pais, anyo_inicio, anyo_fin) {
  req(pais) # comprobamos que se ha seleccionado el país correspondiente

  tsibble::tsibble( # Creación de la serie temporal que se dibujará con hchart
    date = owid_population$Year,
    population = owid_population$`Population (historical estimates)`,
    location = owid_population$Entity,
    index = date,
    key = location) |>
    filter(location == pais) |>
    filter(date >= anyo_inicio & date <= anyo_fin) |>
    highcharter::hchart("line", hcaes(x = date, y = population, group = location))
}
```


[comment 01]: # Creación de la primera columna del cuadro de mando 

Column {.sidebar data-width=230}
--------------------------------------------------

[comment 02]: # Creación menu selección campos 

```{r}
selectInput(
  "country", # nombre de uso interno del desplegable. Se accede a los datos del desplegable haciendo input$country
  label = "Selección de Regiones:", # etiqueta del campo para presentar en el cuadro de mando
  choices =  unique(owid_population$Entity), # vector con las opciones para seleccionar 
  selected = c("Europe","North America","Asia","Africa"), # la opción seleccionada por defecto
  multiple = TRUE # opción para indicar que se seleccionan varios inputs a la vez 
)
```


```{r}
selectInput(
  "yearinit", 
  label = "Start year:",
  choices =  unique(owid_population$Year), 
  selected = first(owid_population$Year)
)
```

```{r}
selectInput(
  "yearend",
  label = "End year:",
  choices =  unique(owid_population$Year),
  selected = last(owid_population$Year)
)
```

[comment 02c]: # Botón que dispara el dibujado de las 4 gráficas: mientras no se pulsa, los cambios en los desplegables no actualizan los gráficos

```{r}
shiny::actionButton("dibujar", "Dibujar gráficas")
```

```{r}
# eventReactive solo se recalcula cuando se pulsa el actionButton "dibujar";
# guarda en una lista los valores de los desplegables en ese momento
seleccion <- shiny::eventReactive(input$dibujar, {
  list(
    country = input$country,
    yearinit = input$yearinit,
    yearend = input$yearend
  )
})
```

[comment 03]: # Creación de la segunda columna del cuadro de mando

Column
--------------------------------------------------

[comment 04]: # Inclusión de 2 gráficos con hchart con los 2 primeros países. El string ### es necesario para fijar cada gráfico y se usa también para añadir un título 

###  

[comment 05]: # Creación de un widget con renderHighchart

```{r}
highcharter::renderHighchart({
  datos <- seleccion() # valores de los desplegables en el momento del último clic
  dibujar_poblacion(datos$country[1], datos$yearinit, datos$yearend)
})
```

###

```{r}
highcharter::renderHighchart({
  datos <- seleccion()
  dibujar_poblacion(datos$country[2], datos$yearinit, datos$yearend)
})
```

[comment 06]: # Creación de la tercera columna del cuadro de mando 

Column
--------------------------------------------------

[comment 07]: # Inclusión de 2 gráficos con hchart con el tercero y cuarto país

### 


```{r}
highcharter::renderHighchart({
  datos <- seleccion()
  dibujar_poblacion(datos$country[3], datos$yearinit, datos$yearend)
})
```

###

```{r}
highcharter::renderHighchart({
  datos <- seleccion()
  dibujar_poblacion(datos$country[4], datos$yearinit, datos$yearend)
})
```













