library(reactable)
library(htmltools)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.4     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(readr)
turnout_country <- read_delim("~/noobsQA/EU_politics/turnout-country.csv", 
    ";", escape_double = FALSE, trim_ws = TRUE) %>% 
  filter(YEAR == 2019) %>% select(-YEAR) %>% 
  rename(
    "country" = "COUNTRY_ID",
    "rate" = "RATE"
  ) %>% 
  select(-UPDATE_STATUS, -UPDATE_TIME) 
## Parsed with column specification:
## cols(
##   YEAR = col_double(),
##   COUNTRY_ID = col_character(),
##   RATE = col_double(),
##   UPDATE_STATUS = col_character(),
##   UPDATE_TIME = col_datetime(format = "")
## )
turnout_country= turnout_country %>% 
  mutate(F1 = rnorm(n= nrow(turnout_country)) %>% round(),
         F2 = rnorm(n= nrow(turnout_country), mean = 100, sd = 10) %>% round(),
         MoV = (F2 - mean(F2)) %>% round(2)) 
make_color_pal <- function(colors, bias = 1) {
  get_color <- colorRamp(colors, bias = bias)
  function(x) rgb(get_color(x), maxColorValue = 255)
}
good_color <- make_color_pal(c("#ffffff", "#f2fbd2", "#c9ecb4", "#93d3ab", "#35b0ab"), bias = 2)


bar_chart <-
  function(label,
           width = "100%",
           height = "13px",
           fill = "#00bfc4",
           background = NULL) {
    bar <-
      div(style = list(
        background = fill,
        width = width,
        height = height
      ))
    chart <-
      div(style = list(
        flexGrow = 1,
        marginLeft = "8px",
        background = background
      ),
      bar)
    div(style = list(display = "flex", alignItems = "center"), label, chart)
  }
tbl_EU = turnout_country %>%
  reactable(columns = list(
    rate = colDef(
      style = function(value) {
        if (value > 50) {
          color <- "#008000"
        } else if (value < 50) {
          color <- "#e00000"
        } else {
          color <- "#777"
        }
        list(color = color, fontWeight = "bold")
      }
    ),
    # country = colDef(
    #   defaultSortOrder = "asc",
    #   minWidth = 200,
    #   headerStyle = list(fontWeight = 700),
    #   cell = function(value, index) {
    #     div(
    #       class = "country",
    #       img(
    #         class = "flag",
    #         alt = paste(value, "flag"),
    #         src = sprintf("flags/%s.png", value)
    #       ),
    #       div(class = "country-name", value),
    #       # div(class = "record", sprintf("%s vote rate", turnout_country[index, "rate"]))
    #     )
    #   }
    # ),
    country = colDef(
      minWidth = 145,
      class = "cell",
      cell = function(value, index) {
        ### Team logos from images folder
        img_src <- knitr::image_uri(sprintf("flags/%s.png", value))
        image <- img(class = "flag",
                     src = img_src,
                     alt = value)
        div(class = "country",
            image,
            ### Team name
            div(class = "country-name", value)#,
            ### Team record
            # div(class = "record",  sprintf("(%s)", NFL_table_clean[index, "Record"]))
            )
      }
    ),
    F1 = colDef(
      name = "Factor 1",
      style = function(value) {
        value
        normalized <-
          (value - min(turnout_country$F1)) / (max(turnout_country$F1) - min(turnout_country$F1))
        color <- good_color(normalized)
        list(background = color)
      }
    ),
    F2 = colDef(
      name = "Points Scored",
      align = "left",
      ### Add column border to left side of column
      class = "border-left cell number",
      headerStyle = list(fontWeight = "500"),
      cell = function(value) {
        ### Calculate width of bar color to display
        width <-
          paste0(value / max(turnout_country$F2) * 100, "%")
        bar_chart(value,
                  width = width,
                  fill = "#ef8a62",
                  background = "#e1e1e1")
      }
    ),
    MoV = colDef(
      maxWidth = 55,
      ### Add column border to right side of column
      class = "cell number border-right ",
      headerStyle = list(fontWeight = "500"),
      ### For any positive number, add "+" sign. For any negative number leave as is
      cell = function(value) {
        if (value > 0)
          paste0("+", value)
        else
          value
      },
      ### For any positive number, assign green color. For any negative number assign red color
      style = function(value) {
        if (value > 0) {
          color <- "#008000"
        } else if (value < 0) {
          color <- "#e00000"
        } else {
          color <- "#777"
        }
        list(color = color)
      }
    )
  ))



div(class = "standings",
  div(class = "title",
    h2("EU parliament votes"),
    "Source EU gov data"
  ),
  tbl_EU,
  "Work in progress"
)

EU parliament votes

Source EU gov data
Work in progress
# .flag {
#   margin-right: 8px;
#   height: 21px;
#   border: 1px solid #f0f0f0;
# }

/* Team column formatting */
.country {
  display: flex;
  align-items: baseline;
}
.flag {
  margin-right: 10px;
  height: 24px;
}
.country-name {
  font-size: 14px;
  font-weight: 700;
}
# .record {
#   margin-left: 4px;
#   color: #999;
#   font-size: 13px;
# }