# Opciones ----
options(scipen = 999)

# Librerias ----
library(tidyverse)
library(sf)
library(leaflet)
library(plotly)
library(DT)
library(readxl)
library(shinyWidgets)
library(shinydashboard)
library(shinycssloaders)
library(rsconnect)

# Bases de datos ----
datos <- read_xlsx("www/datos2.xlsx")
meta <- read_xlsx("www/metadatos2.xlsx")
catalogo <- readRDS("www/catalogoEntidades.rds")
mapa <- st_read("https://raw.githubusercontent.com/JuveCampos/Shapes_Resiliencia_CDMX_CIDE/master/geojsons/Division%20Politica/DivisionEstatal.geojson",
                quiet = TRUE)
textos <- readxl::read_xlsx("www/textos.xlsx")

# Vector de opciones con nombre
opcionesIndicadores <- unique(datos$no)
names(opcionesIndicadores) <- paste0(meta$no,
                                     "-",
                                     meta$indicador)

# Mapa, serie de tiempo, grafica de Barras

# Datos variables (datos de entrada) ----
num <- 1 # Varia para todos los indicadores
anio <- 2008 # Variaba para las barras y para el mapa
edo_interes <- c("Morelos", "Colima") # Esto solo varia para la ts

# Bases de datos intermedias ----
dg <- datos %>%
  filter(no == num) %>%
  filter(year == anio) %>%
  left_join(catalogo)

mg <- meta %>%
  filter(no == num)




# Grafica de barras ----

grafica_barras <- function(dg, mg){

  if(mg$sentido == "Menos es mejor"){

    dg %>%
      ggplot(aes(x = reorder(ent, -valor),
                 y = valor)) +
      geom_col(fill = "olivedrab") +
      coord_flip() +
      scale_y_continuous(expand =
                           expansion(c(0,0.2), 0.5)) +
      labs(x = "", y = "",
           title = mg$indicador,
           subtitle = paste0("Año: ", first(dg$year)),
           caption = str_wrap(paste0("Fuente: ", mg$fuente, "\n",
                                     "Unidad de medida: ", mg$umedida), 100)) +
      theme_bw()  +
      theme(text = element_text(family = "Arial"),
            plot.title = element_text(hjust = 0.5, face = "bold"),
            plot.subtitle = element_text(hjust = 0.5))


  } else {

    dg %>%
      ggplot(aes(x = reorder(ent, valor),
                 y = valor)) +
      geom_col(fill = "olivedrab") +
      coord_flip() +
      scale_y_continuous(expand =
                           expansion(c(0,0.2), 0.5)) +
      labs(x = "", y = "",
           title = mg$indicador,
           subtitle = paste0("Año: ", first(dg$year)),
           caption = str_wrap(paste0("Fuente: ", mg$fuente, "\n",
                                     "Unidad de medida: ", mg$umedida), 100)) +
      theme_bw()  +
      theme(text = element_text(family = "Arial"),
            plot.title = element_text(hjust = 0.5, face = "bold"),
            plot.subtitle = element_text(hjust = 0.5))

  }


}

# Serie de tiempo ----

# grafica_serie_tiempo(num = 1,
#                      edo_interes = "Morelos",
#                      mg = mg)

grafica_serie_tiempo <- function(num, edo_interes, mg){

dts <- datos %>%
    filter(no == num) %>%
    left_join(catalogo) %>%
    filter(ent %in% edo_interes)

plt <- dts %>%
  ggplot(aes(x = year,
             y = valor,
             group = ent,
             color = ent)) +
  geom_line() +
  geom_point(shape = 21, color = "black") +
  scale_x_continuous(breaks = seq(min(dts$year), max(dts$year), by = 2)) +
  theme_bw()  +
  theme(text = element_text(family = "Arial"),
        plot.title = element_text(hjust = 0.5, face = "bold"),
        plot.subtitle = element_text(hjust = 0.5)) +
  labs(color = "Entidad",
       shape = "Entidad",
       fill = "Entidad",
       x = "",
       y = "",
       title = mg$indicador,
       subtitle = mg$periodo,
       caption = str_wrap(paste0("Fuente: ", mg$fuente, "\n",
                                 "Unidad de medida: ", mg$umedida), 100))

ggplotly(plt)

}

# Mapa ----

# mapa_leaflet_funcion(mg, dg)

mapa_leaflet_funcion <- function(mg, dg){

mapa_leaflet <- left_join(mapa,
                            dg,
                            by = c("CVE_EDO" = "cve_ent"))

if (mg$sentido == "Menos es mejor"){
  pal <- colorNumeric(
    palette = "magma",
    domain = mapa_leaflet$valor,
    rev = TRUE
  )
} else {
  pal <- colorNumeric(
    palette = "magma",
    domain = mapa_leaflet$valor
  )
}

label <- paste0("Entidad: ", mapa_leaflet$ENTIDAD)
popup <- paste0("<b>Entidad: </b>", mapa_leaflet$ENTIDAD, "<br>",
                "<b>Indicador: </b>", mg$indicador, "<br>",
                "<b>Valor: </b>", mapa_leaflet$valor, "<br>")

mapa_leaflet %>%
  leaflet(options = leafletOptions(minZoom = 5)) %>%
  setMaxBounds(lng1 = -86.72,
               lat1 = 14.52,
               lng2 = -117.13,
               lat2 = 32.53) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(label = label,
              popup = popup,
              weight = 0.6,
              fillColor = pal(mapa_leaflet$valor),
              fillOpacity = 0.9,
              color = "black",
              opacity = 1) %>%
  addLegend(title = str_replace_all(str_wrap(mg$indicador, 20),
                                    pattern = "\n",
                                    replacement =  "<br>"),
            pal = pal,
            values = mapa_leaflet$valor,
            position = "bottomleft")
}

