
  
options(shiny.sanitize.errors = FALSE)
options(shiny.host = '0.0.0.0')
options(shiny.port = 8080)

# required external directories are defined

figs_folder_seti = "www/figures"
figs_folder_servimet = "www/external_repository/SERVIMET/cartas_color"
figs_folder_mjo_bom = "www/external_repository/mjo_repo/bom/RMM_40_days"
figs_folder_mjo_ncep = "www/external_repository/mjo_repo/ncpe"
figs_folder_jma = "www/external_repository/JMA"


library(shiny)
library(shinyBS)
library(dygraphs)
library(leaflet)
library(dplyr)

library(shinythemes)

library(xts)          # To make the convertion data-frame / xts format
library(tidyverse)
library(lubridate)

library(RCurl)
library(R.matlab)

library(sf)
# library(tmap)  # 20251205 Incompatible con Debian 12
library(spData)

library(sp)
library(ncdf4)
library(leaflet)
library(raster)
library(rjson)

library(rgdal)

pdf(NULL)


shinyServer(function(input, output) {
  
  # # Help
  # observeEvent(input$contact,
  #              showModal("contactlExample", "Last SETI forecast available", "go",
  #                      "Hola"
  #              )
  # )
  
  observeEvent(input$Disclaimer, {
    showModal(modalDialog(
      title = "Disclaimer",
      "Please note that these products are for experimental 
      use and do not represent official forecasts issued by 
      any public or private institution.",
      br(""),
      strong("Contact:"),
      "Christian Segura (chseguraguzman@gmail.com), Martín Jacques Coper (martinjacques@udec.cl)",
      
      easyClose = TRUE
    ))
  })
  
  # JMA ###############
  output$select.figs_jma <- renderUI(expr = selectInput(inputId = 'file.name_jma',
                                                             label = '',
                                                             # choices = grep(list.files(path = file.path("../ETI/figures/")), pattern='.png', invert = TRUE, value=TRUE))
                                                             #choices = rev(list.files(path = file.path("../ETI/figures/"))))
                                                             choices = rev(list.files(path = file.path( figs_folder_jma )))
  )
  )
  
  output$selected_picture_jma <- renderText({
    src <- paste0("external_repository/JMA/",input$file.name_jma)
    HTML('<img src="',src,'", width="70%">')
  }
  )
  
  # SERVIMET ###############
  output$select.figs_servimet <- renderUI(expr = selectInput(inputId = 'file.name_servimet',
                                                    label = '',
                                                    # choices = grep(list.files(path = file.path("../ETI/figures/")), pattern='.png', invert = TRUE, value=TRUE))
                                                    #choices = rev(list.files(path = file.path("../ETI/figures/"))))
                                                    choices = rev(list.files(path = file.path( figs_folder_servimet )))
                                                    )
                                          )
  
  output$selected_picture_servimet <- renderText({
    src <- paste0("external_repository/SERVIMET/cartas_color/",input$file.name_servimet)
    HTML('<img src="',src,'", width="50%">')
    }
    )
  
  # MJO BOM ###############
  output$select.figs_mjo_bom <- renderUI(expr = selectInput(inputId = 'file.name_mjo_bom',
                                                             label = '',
                                                             choices = rev(list.files(path = file.path( figs_folder_mjo_bom )))
                                                            )
                                         )
  
  output$selected_picture_mjo_bom <- renderText({
    src <- paste0("external_repository/mjo_repo/bom/RMM_40_days/",input$file.name_mjo_bom)
    HTML('<img src="',src,'", width="50%">')
  }
  )
  
  # MJO NCEP ###############
  output$select.figs_mjo_ncep <- renderUI(expr = selectInput(inputId = 'file.name_mjo_ncep',
                                                            label = '',
                                                            choices = rev(list.files(path = file.path( figs_folder_mjo_ncep )))
                                                            )
                                          )
  
  output$selected_picture_mjo_ncep <- renderText({
    src <- paste0("external_repository/mjo_repo/ncpe/",input$file.name_mjo_ncep)
    HTML('<img src="',src,'", width="65%">')
  }
  )
  
  # SETI ###############                             
  output$select.file <- renderUI(expr = selectInput(inputId = 'file.name',
                                                    label = '',
                                                    # choices = grep(list.files(path = file.path("../ETI/figures/")), pattern='.png', invert = TRUE, value=TRUE))
                                                    #choices = rev(list.files(path = file.path("../ETI/figures/"))))
                                                    choices = rev(list.files(path = file.path( figs_folder_seti )))
                                                    )
                                 )
  
  output$selected_picture <- renderText({
    src <- paste0("figures/",input$file.name)
    HTML('<img src="',src,'", width="100%">')
    }
    )
    
    output$last_picture_front <- output$last_picture2 <- output$last_picture<-renderText({
        src <- paste0("upload/fig_01.png")
        # src <- gsub(" ", "", paste("https://www2.dgeo.udec.cl/Public/hw_dynamic/ETI/figures/SETI%20forecast%20From%20GFS%20",fecha(),"%2000%3A00%3A00.png"))
        # src <- gsub(" ", "", src)
        HTML('<img src="',src,'", width="100%">')
        }
        )
    
    output$value_display <- renderText({ input$radio_display })
    
    output$value <- renderText({
        req(input$go)
        isolate(input$password)
        }
        )
    
    # output$dygraph_analysis <- renderDygraph({
    #     data <- read.csv("data/SETI.csv")
    #     time_anl <- data[1]
    #     real_time <- as.Date(unlist(time_anl), format = "%Y-%m-%d" )
    #     # real_time <- as.POSIXlt(unlist(time_anl), "%d-%b-%Y %H:%M:%S" )
    #     # as.Date(df$Date, format =  "%m/%d/%Y %H:%M:%S")
    #     seti_anl <- data[2]
    #     
    #     don <- xts(x = seti_anl, order.by = real_time)
    #     
    #     p <- dygraph(don, main = "") %>%
    #         
    #         dyOptions(labelsUTC = FALSE, fillGraph=TRUE, fillAlpha=0.99, drawGrid = TRUE, colors="#D8AE5A") %>%
    #         dySeries("Var2",label="SETI") %>%
    #         dyRangeSelector() %>%
    #         dyCrosshair(direction = "vertical") %>%
    #         dyHighlight(highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.99, hideOnMouseOut = TRUE)  %>%
    #         dyRoller(rollPeriod = 1) %>%
    #         dyAxis("y", label = "Standardized Extra Tropical Index [SETI]", valueRange = c(-5, 5)) %>%
    #         dyAxis("x", label = "Time Selector") %>%
    #         dyShading(from = "-1", to = "1", axis = "y", color = "#CCEBD6")
    # })
    
    data_output_folder = "www/upload"
    output$dygraph_forecast <- renderDygraph({
        #data <- read.csv("../ETI/output/SETI_all.csv")
        data <- read.csv(paste0(data_output_folder,"/SETI_all.csv"))
        time_anl <- data[1]
        # real_time <- as.Date(unlist(time_anl), format = "%Y-%m-%d" )
        real_time <- as.POSIXct(unlist(time_anl))
        # seti_anl <- data[2:24]
        seti_anl <- data[c(5:24, 2:4)]
        don <- xts(x = seti_anl, order.by = real_time)
        
        names_vars<- colnames(don)
        new_name <- c("e1", "e2", "e3"
                      , "e4", "e5", "e6", "e7", "e8", "e9", "e10", "e11", "e12"
                      , "e13", "e14", "e15", "e16", "e17", "e18", "e19", "e20"
                      , "anl", "oper", "eavg")
        color_series <- c(rep("#DFA770", 20), "#0048BA", "#3B7A57", "#E52B50")
        
        colnames(don) <- new_name
        
        p <- dygraph(don, main = "") %>%
            dyOptions(labelsUTC = FALSE, fillGraph=FALSE, fillAlpha=0.99, drawGrid = TRUE, colors=color_series, stepPlot = FALSE, strokeWidth = 2) %>%
            # dySeries(names_vars, label=new_name) %>%
            dyRangeSelector() %>%
            dyCrosshair(direction = "vertical") %>%
            # dyHighlight(highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.99, hideOnMouseOut = TRUE)  %>%
            # dyRoller(rollPeriod = 1) %>%
            dyAxis("y", label = "Standardized Extra Tropical Index [SETI]", valueRange = c(-5, 5)) %>%
            dyAxis("x", label = "Time Selector")  %>%
          # dyLegend(show = "follow") %>%
          dyLegend(labelsDiv = "legend_dygraph_forecast") %>%
          dyHighlight(highlightCircleSize = 5, 
                      highlightSeriesBackgroundAlpha = 0.3,
                      hideOnMouseOut = TRUE) %>%
          dyCSS(textConnection(".few .dygraph-legend > span.highlight { border: 1px solid grey; }")) %>%
            dyShading(from = "-1", to = "1", axis = "y", color = "#CCEBD6")
    })
    
    data <- read.csv("www/upload/SETI_all.csv")
    # colnames(data) <- c("Date","SETI")
    
    # aux  <- reactive({input$select})
    
    output$downloadData2 <- output$downloadData <- downloadHandler(
        # if (input$select == 1) {
        filename = function() {
            # paste("SETI_timeserie_", Sys.Date(), ".csv", sep="")
          paste("SETI", ".csv", sep="")
        },
        content = function(file) {
            write.csv(data, file, row.names = FALSE)
        }
        # }
        # if (input$select == 2) {
        #   filename = function() {
        #     paste("SETI_timeserie_", Sys.Date(), ".xlsx", sep="")
        #   },
        # content = function(file) {
        #   write.xlsx(data, file, row.names = FALSE)
        # }
        # }
        # if (input$select == 2) {
        # filename = function() {
        #   paste("SETI_timeserie_", Sys.Date(), ".mat", sep="")
        # },
        # content = function(file) {
        #   writeMat(data, file, row.names = FALSE)
        # }
        # }
    )
    
    alt <- c(527,
             225,
             151,
             92,
             21,
             347)
    lats <- c(-33.4450,
              -34.9664,
              -36.5872,
              -38.7700,
              -39.6506,
              -43.1889)
    lons <- c(-70.6828,
              -71.2167,
              -72.0400,
              -72.6369,
              -73.0808,
              -71.8525)
    colores <- c( "red", "red", "red", "blue", "blue", "blue")
    radios <- c(1, 1, 1, 1, 1, 1)*3
    nombre <- c('santiago','curico','chillan','temuco','valdivia','futaleufu')
    
    m <- leaflet() %>%
      addTiles() %>%
      addCircleMarkers(data = alt, lat = lats, lng = lons, label = nombre, color = colores, radius = radios, popup = alt) %>%
      setView(lng = -72,
              lat = -35,
              zoom = 4 ) 
    output$weather_stations <- renderLeaflet(m)
    
    
    m2 <- leaflet() %>%
      addTiles() %>%
      addCircleMarkers(data = alt[2], lat = lats[2], lng = lons[2], label = nombre[2], color = colores[2], radius = radios[2]*1.5, popup = alt[2]) %>%
      setView(lng = -72,
              lat = -35,
              zoom = 5 ) 
    output$weather_station_curico <- renderLeaflet(m2)
    
    
    
    data_output_folder = "www/upload"
    output$weatherstation <- renderDygraph({
      #data <- read.csv("../ETI/output/SETI_all.csv")
      data <- read.csv(paste0(data_output_folder,"/tmp_up.csv"))
      time_anl <- data[1]
      # real_time <- as.Date(unlist(time_anl), format = "%Y-%m-%d" )
      real_time <- as.POSIXct(unlist(time_anl))
      # seti_anl <- data[2:24]
      seti_anl <- data[c(4:23, 2:3)]
      don <- xts(x = seti_anl, order.by = real_time)
      
      names_vars<- colnames(don)
      new_name <- c("e1", "e2", "e3"
                    , "e4", "e5", "e6", "e7", "e8", "e9", "e10", "e11", "e12"
                    , "e13", "e14", "e15", "e16", "e17", "e18", "e19", "e20"
                    , "oper", "eavg")
      color_series <- c(rep("#DFA770", 20), "#3B7A57", "#E52B50")
      
      colnames(don) <- new_name
      
      p <- dygraph(don, main = "") %>%
        dyOptions(labelsUTC = FALSE, fillGraph=FALSE, fillAlpha=0.99, drawGrid = TRUE, colors=color_series, stepPlot = FALSE, strokeWidth = 2) %>%
        # dySeries(names_vars, label=new_name) %>%
        dyRangeSelector() %>%
        dyCrosshair(direction = "vertical") %>%
        # dyHighlight(highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.99, hideOnMouseOut = TRUE)  %>%
        # dyRoller(rollPeriod = 1) %>%
        # dyAxis("y", label = "Temperature [°C]", valueRange = c(-5, 5)) %>%
        dyAxis("y", label = "Temperature [°C]") %>%
        dyAxis("x", label = "Time Selector")  %>%
        dyLegend(labelsDiv = "legend_dygraph_weatherstation") %>%
        dyHighlight(highlightCircleSize = 5, 
                    highlightSeriesBackgroundAlpha = 0.3,
                    hideOnMouseOut = TRUE)
        # dyShading(from = "-1", to = "1", axis = "y", color = "#CCEBD6")
    })
    
    output$weatherstation2 <- renderDygraph({
      #data <- read.csv("../ETI/output/SETI_all.csv")
      data <- read.csv(paste0(data_output_folder,"/tmp_bottom.csv"))
      time_anl <- data[1]
      # real_time <- as.Date(unlist(time_anl), format = "%Y-%m-%d" )
      real_time <- as.POSIXct(unlist(time_anl))
      # seti_anl <- data[2:24]
      seti_anl <- data[c(4:23, 2:3)]
      don <- xts(x = seti_anl, order.by = real_time)
      
      names_vars<- colnames(don)
      new_name <- c("e1", "e2", "e3"
                    , "e4", "e5", "e6", "e7", "e8", "e9", "e10", "e11", "e12"
                    , "e13", "e14", "e15", "e16", "e17", "e18", "e19", "e20"
                    , "oper", "eavg")
      color_series <- c(rep("#DFA770", 20), "#3B7A57", "#E52B50")
      
      colnames(don) <- new_name
      
      p <- dygraph(don, main = "") %>%
        dyOptions(labelsUTC = FALSE, fillGraph=FALSE, fillAlpha=0.99, drawGrid = TRUE, colors=color_series, stepPlot = FALSE, strokeWidth = 2) %>%
        # dySeries(names_vars, label=new_name) %>%
        dyRangeSelector() %>%
        dyCrosshair(direction = "vertical") %>%
        # dyHighlight(highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.99, hideOnMouseOut = TRUE)  %>%
        # dyRoller(rollPeriod = 1) %>%
        # dyAxis("y", label = "Temperature [°C]", valueRange = c(-5, 5)) %>%
        dyAxis("y", label = "Temperature [°C]") %>%
        dyAxis("x", label = "Time Selector")  %>%
        dyLegend(labelsDiv = "legend_dygraph_weatherstation2") %>%
        dyHighlight(highlightCircleSize = 5, 
                    highlightSeriesBackgroundAlpha = 0.3,
                    hideOnMouseOut = TRUE)
        # dyShading(from = "-1", to = "1", axis = "y", color = "#CCEBD6")
    })
    
    
    
    # output$weatherstation <- renderDygraph({
    #   data <- est[,2]
    #   data <- as.numeric(data)
    #   data[data==-9999] <- NA 
    #   time_anl <- fechas
    #   real_time <- as.Date(unlist(time_anl), format = "%Y-%m-%d" )
    #   # seti_anl <- data[2:24]
    #   don <- xts(x = data, order.by = real_time)
    #   
    #   names_vars <- nombre[2]
    #   # new_name <- c("e1", "e2", "e3"
    #   #               , "e4", "e5", "e6", "e7", "e8", "e9", "e10", "e11", "e12"
    #   #               , "e13", "e14", "e15", "e16", "e17", "e18", "e19", "e20"
    #   #               , "SETI", "oper", "eavg")
    #   # color_series <- c(rep("#DFA770", 20), "#0048BA", "#3B7A57", "#E52B50")
    #   # 
    #   # colnames(don) <- new_name
    #   
    #   p <- dygraph(don, main = "") %>%
    #     dyOptions(labelsUTC = FALSE, fillGraph=FALSE, fillAlpha=0.99, drawGrid = TRUE, stepPlot = FALSE, strokeWidth = 2) %>%
    #     # dySeries(names_vars, label=new_name) %>%
    #     dyRangeSelector() %>%
    #     dyCrosshair(direction = "vertical") %>%
    #     # dyHighlight(highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.99, hideOnMouseOut = TRUE)  %>%
    #     # dyRoller(rollPeriod = 1) %>%
    #     dyAxis("y", label = "Tx [°C]", valueRange = c(min(data, na.rm = TRUE)-5, max(data, na.rm = TRUE)+5)) %>%
    #     dyAxis("x", label = "Time Selector")  %>%
    #     dyShading(from = "-1", to = "1", axis = "y", color = "#CCEBD6")
    # })
    
    # output$downloadData <- downloadHandler(
    #   filename = function() {
    #     paste(input$dataset, ".csv", sep = "")
    #   },
    #   content = function(file) {
    #     write.csv(datasetInput(), file, row.names = FALSE)
    #   }
    # )
    
}
)
