server <- function(input, output, session) {
  
  countries <- c("Spain", "England", "Germany", "Italy", "France", "Portugal")
  
  #### European performance over time ####
  time_plot_debounced <- debounce(reactive(input$time_plot), millis = 200)
  time_plot_level <- reactive({
    val <- time_plot_debounced()
    if (is.null(val)) 0 else val
  })
  
  time_plot_selected_data <- reactive({
    season_league_full_dataset %>% filter(Country == countries[time_plot_level() + 1])
  })
  
  output$european_performance_over_time_plot <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)
    
    custom_plotly(data = time_plot_selected_data(), x = ~Season, y = ~European_performance, type = "scatter", mode = "lines", hoverinfo = "none",
                  xaxis_title = "Season", yaxis_title = "European performance", width = width) %>%
      layout(yaxis = list(range = c(0, 70)))
  })
  
  
  #### League characteristics ####
  league_averages_plot_debounced <- debounce(reactive(input$league_averages_plot), millis = 200)
  league_averages_plot_level <- reactive({
    val <- league_averages_plot_debounced()
    if (is.null(val)) 0 else val
  })
  
  league_averages_plot_selected_data <- reactive({
    average_country_metrics_scaled %>% filter(Country == countries[league_averages_plot_level() + 1])
  })
  
  #plotting radar chart
  output$league_characteristics_plot <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)
    
    country_data <- league_averages_plot_selected_data()
    values <- as.numeric(country_data[1, -1])
    
    custom_plotly(type = 'scatterpolar', fill = 'toself', hoverinfo = "none", xaxis_title = "", yaxis_title = "", width = width) %>%
      add_trace(
        r = c(values, values[1]),
        theta = c(gsub("_", " ", names(country_data)[-1]), gsub("_", " ", names(country_data)[-1][1]))
      ) %>%
      layout(
        polar = list(radialaxis = list(range = c(0,1))),
        showlegend = FALSE
      )
  })
  
  
  #### Basic group profiling ####
  basic_profiless_plot_debounced <- debounce(reactive(input$basic_profiling_plot), millis = 200)
  basic_profiless_plot_level <- reactive({
    val <- basic_profiless_plot_debounced()
    if (is.null(val)) 0 else val
  })
  
  basic_profiless_plot_selected_data <- reactive({
    european_performance_groups_characteristics %>% filter(performance_group == basic_profiless_plot_level() + 1)
  })
  
  #plotting radar chart
  output$basic_profiles_characteristic_plot  <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)
    
    group_data <- basic_profiless_plot_selected_data()
    values <- as.numeric(group_data[1, 2:10])
    
    custom_plotly(type = 'scatterpolar', fill = 'toself', hoverinfo = "none", xaxis_title = "", yaxis_title = "", width = width) %>%
      add_trace(
        r = c(values, values[1]),
        theta = c(gsub("_", " ", names(group_data)[2:10]), gsub("_", " ", names(group_data)[2:10][1]))
      ) %>%
      layout(
        polar = list(radialaxis = list(range = c(-0.4,0.4))),
        showlegend = FALSE
      )
  })
  
  
  #### Regression coefficients one season ####
  regression_current_year_plot_debounced <- debounce(reactive(input$regression_current_year_plot), millis = 200)
  regression_current_year_plot_level <- reactive({
    val <- regression_current_year_plot_debounced()
    if (is.null(val)) 0 else val
  })
  
  one_season_full_coefficients <- list(panel_all_robust_theory, panel_pc, indices_all_plotting_data)
  coefficient_one_year_data <- reactive({
    one_season_full_coefficients[[regression_current_year_plot_level() + 1]]
  })
  
  #plotting coefficients
  output$regression_coefficients_current_plot <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)
    if (regression_current_year_plot_level() %in% c(0,1)){
      #version with all in one
      coefficient_plot_function(regression_result = coefficient_one_year_data(), width = width)
    } else if (regression_current_year_plot_level() == 2){
      #indices version (multiple regressions combined in one)
      coefficient_plot_function(regression_result = NULL, coefficient_plotting_data = coefficient_one_year_data(), width = width)
    }
  })
  
  
  #### Regression coefficients next season ####
  regression_next_year_plot_debounced <- debounce(reactive(input$regression_next_year_plot), millis = 200)
  regression_next_year_plot_level <- reactive({
    val <- regression_next_year_plot_debounced()
    if (is.null(val)) 0 else val
  })
  
  next_season_full_coefficients <- list(panel_all_lead, panel_lead_pc, indices_lead_plotting_data)
  coefficient_next_year_data <- reactive({
    next_season_full_coefficients[[regression_next_year_plot_level() + 1]]
  })
  
  #plotting coefficients
  output$regression_coefficients_next_plot <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)
    if (regression_next_year_plot_level() %in% c(0,1)){
      #version with all in one
      coefficient_plot_function(regression_result = coefficient_next_year_data(), width = width, range_val = 15)
    } else if (regression_next_year_plot_level() == 2){
      #indices version (multiple regressions combined in one)
      coefficient_plot_function(regression_result = NULL, coefficient_plotting_data = coefficient_next_year_data(), width = width, range_val = 15)
    }
  })
  
  
  #### Regression coefficients by competition ####
  regression_competition_plot_debounced <- debounce(reactive(input$regression_competition_plot), millis = 200)
  regression_competition_plot_level <- reactive({
    val <- regression_competition_plot_debounced()
    if (is.null(val)) 0 else val
  })
  
  comp_breakdown_season_full_coefficients <- list(panel_all_CL, panel_pc_CL, indices_comp_breakdown_plotting_data)
  coefficient_comp_breakdown_data <- reactive({
    comp_breakdown_season_full_coefficients[[regression_competition_plot_level() + 1]]
  })
  
  #plotting coefficients
  output$regression_coefficients_competition_plot <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)
    if (regression_competition_plot_level() %in% c(0,1)){
      #version with all in one
      coefficient_plot_function(regression_result = coefficient_comp_breakdown_data(), width = width, range_val = 5)
    } else if (regression_competition_plot_level() == 2){
      #indices version (multiple regressions combined in one)
      coefficient_plot_function(regression_result = NULL, coefficient_plotting_data = coefficient_comp_breakdown_data(), width = width, range_val = 5)
    }
  })
  
  
  #### Clustering ####
  clustering_plot_debounced <- debounce(reactive(input$clustering_plot), millis = 200)
  clustering_plot_level <- reactive({
    val <- clustering_plot_debounced()
    if (is.null(val)) 0 else val
  })

  clustering_plot_selected_data <- reactive({
    plotting_cluster_data %>% filter(cluster == clustering_plot_level() + 1)
  })

  #plotting radar chart
  output$clustering_characteristics_plot  <- renderPlotly({
    width <- ifelse(is.null(input$screen_width), 760, input$screen_width)

    group_data <- clustering_plot_selected_data()
    values <- as.numeric(group_data[1, 2:10])

    custom_plotly(type = 'scatterpolar', fill = 'toself', hoverinfo = "none", xaxis_title = "", yaxis_title = "", width = width) %>%
      add_trace(
        r = c(values, values[1]),
        theta = c(gsub("_", " ", names(group_data)[2:10]), gsub("_", " ", names(group_data)[2:10][1]))
      ) %>%
      layout(
        polar = list(radialaxis = list(range = c(-0.7,1.5))),
        showlegend = FALSE
      )
  })
  
}
