# Packages

library(shiny)
library(shinythemes)
library(dplyr)
library(readr)
library(sf)
library(leaflet)

pirate_attacks_sf_ss2 <-
  read_sf("data/geojson/pirate_attacks_sf_ss2.geojson")

source("pirateIcon.R")

# UI

ui <- fluidPage(
  theme = shinytheme("lumen"),
  titlePanel("Attaques pirates contre des navires"),
  sidebarLayout(
    sidebarPanel(
      # Select type of vessel to plot
      selectInput(
        inputId = "vessel",
        label = strong("Vessel category"),
        choices = unique(pirate_attacks_sf_ss2$vessel_category),
        selected = "Bulk"
      ),
      # Select date range to be plotted
      dateRangeInput(
        "date",
        strong("Date range"),
        start = min(pirate_attacks_sf_ss2$date),
        end = max(pirate_attacks_sf_ss2$date),
        min = min(pirate_attacks_sf_ss2$date),
        max = max(pirate_attacks_sf_ss2$date)
      ),
    ),
    mainPanel(
      leafletOutput("pirateMap"),
      p(),
      tags$a(
        href = "https://github.com/newzealandpaul/Maritime-Pirate-Attacks",
        "Crime at Sea: A Global Database of Maritime Pirate Attacks (1993 - 2020)",
        target = "_blank"
      )
    )
  )
)

# Server

server <- function(input, output) {
  # Filter data
  pirate_attacks_sf_maps <- reactive({
    req(input$date)
    req(input$vessel)
    validate(need(
      !is.na(input$date[1]) &
        !is.na(input$date[2]),
      "Error: Please provide both a start and an end date."
    ))
    validate(need(
      input$date[1] < input$date[2],
      "Error: Start date should be earlier than end date."
    ))
    pirate_attacks_sf_ss2 %>%
      filter(
        vessel_category == input$vessel,
        as.POSIXct(date) > as.POSIXct(input$date[1]) &
          as.POSIXct(date) < as.POSIXct(input$date[2])
      )
    
  })
  
  output$pirateMap <- renderLeaflet({
    source("leaflet_pirate_popuptext.R")
    
    leaflet() %>%
      addTiles() %>%
      addMarkers(
        data = pirate_attacks_sf_maps(),
        popup = paste0(
          "Type: ",
          pirate_attacks_sf_maps()$vessel_category,
          "<br>",
          "Statut: ",
          pirate_attacks_sf_maps()$vessel_status,
          "<br>",
          "Type d'attaque: ",
          pirate_attacks_sf_maps()$attack_type,
          "<br>",
          "Distance de la côte: ",
          round(pirate_attacks_sf_maps()$shore_distance, 2),
          "km",
          "<br>",
          "Date: ",
          pirate_attacks_sf_maps()$date
        ),
        icon = pirateIcon,
        clusterOptions = markerClusterOptions()
      )
  })
}

shinyApp(ui, server)
