knitr::opts_chunk$set(
    echo = FALSE
    
)
library(tidyverse)
library(DT)
getSecs <- function(t) {
  a <- as.numeric(str_extract(t,"^(\\d)"))* 60
  b <- as.numeric(str_extract(t,"(.){5}$"))* 1
  getSecs <- a + b
}

getft <- function(x){
 x * 330
}

orange <- "#e8ab5f"
green <- "#a1ad62"

background_diff <- "#eef0e2"

gray <- "#bbbbbb"
light_gray <- "#f4f4f4"



files <- dir("C:/Users/mutue/OneDrive/Documents/TimeForm/Data/TCharts/", full.names = T) 

tcharts <- files %>%
  map(read_csv, col_names=c("trk",
                            "rnum","rprse","rdt","rdst","srf","pos","sxtnth","pgm","hrse","stime","sdst","srail","samph","sahd","ctime","cpk","cdst","cdlt","camph")) %>%     # read in all the files individually, using
                       # the function read_csv() from the readr package
  reduce(rbind)        # reduce with rbind into one dataframe

tcharts <- tcharts %>% 
  mutate(tc = "pink") %>% 
  mutate(rnum = as.double(str_extract(rnum, "(\\d+)"))) %>% 
  mutate(rprse = as.double(str_extract(rprse, "(\\d+)"))) %>% 
  mutate(sxtnth = sxtnth-1) %>% 
  mutate(grdlss = (cdst- (sxtnth * 330))) %>% 
  mutate(sfps = sdst / stime) %>%
  mutate(sahd = if_else(is.na(sahd),0,sahd)) %>% 
  mutate(ctime = if_else(nchar(ctime)>6,getSecs(ctime),as.numeric(ctime))) %>%
  mutate(sxtnth = getft(sxtnth)) %>% 
  mutate(cfps = as.numeric(cdst) / as.numeric(ctime)) %>%
  group_by(sxtnth) %>% 
  mutate(beatenLengths = cumsum(sahd) - sahd) %>% 
  mutate(beatenLengths =  -beatenLengths*9) %>%
  ungroup() %>% 
  mutate(Finish = pos) %>% 
  mutate(srail = -srail) %>% 
  filter(rnum ==1) %>% 
  filter(sxtnth == 3300) %>% 
  rename(Horse=hrse, DistanceRun = cdst, Sixteenth = sxtnth, GroundLoss = grdlss, OffRail = srail) %>% 
  select(Horse, Sixteenth, DistanceRun, cfps, cdlt, pos, ctime) %>% 
  mutate(dp = round((DistanceRun/max(DistanceRun))*0.35,digits=4)) %>% 
  mutate(tp = round((cfps/max(cfps))*0.90,digits = 4)) %>% 
  arrange(pos) %>% 
  gather(key=group,value =value,dp,tp) %>% 
  mutate(value2 = if_else(group=="dp",DistanceRun, ctime)) %>% 
  arrange(pos)


  

datatable(tcharts)
p<-
ggplot(
  data = tcharts,
  mapping = aes(
    # Y Axis
    y=Horse, 
    # X Axis
    x=value, 
    color = ifelse(cdlt == 0, "zero", group))
) + 
  # Plot lines between points, by Country
  geom_line(
   mapping = aes(group = Horse),
    color = "gray",
    size = 2.5
  ) +
  geom_point(
    # Dot size
    size=4,
    # dot type. Important to be number 19, otherwise we cannot plot the dots 
    # with the colors for different groups
    pch = 19
  ) +
  # Add % for each point
  geom_text(
    # Font size
    size = 4,
    # Set text a little below the dots
    nudge_y = -0.35,
    mapping = 
      aes(
        label = 
          # If country is Germany (the first one), plot numbers with %
          ifelse(pos == 1,
                 # Value_if_True:
                 paste0(as.character(round(value2*1,0)),""),
                 # Value_if_False
                 paste0(as.character(round(value2*1,2)))
                 ),
        color = ifelse(cdlt == 0, "zero", group)

      )
  ) +
  # Change dot colors
  scale_color_manual(
    values = c("blue", "lightgreen", "gray")
  ) +
  # Change scale x axis
  scale_x_continuous(
    # Set limits to 0 and 1.2 (we won't set it to 1 because we neeed some space
    # after 1 to place the values of the differences)
    limits = c(0,1.2),
    # Show tick marks at every 25%
    breaks = seq(0,1,.25),
    # Change scale to percent
    labels = scales::percent
  ) +
  # Expand y axis scale so that the legend can fit
  scale_y_discrete(
    expand = expand_scale(add=c(0.65,1))
  ) +
  # Add white rectangle to set the area where the values of the differences will
  # be
  geom_rect(
    mapping = aes(xmin = 1.01, xmax = Inf , ymin = -Inf, ymax = Inf),
    fill = "white",
    color = "white"
  ) +
  # Add rectangle with correct banground color for the differences
  geom_rect(
    mapping = aes(xmin = 1.05, xmax = 1.15 , ymin = -Inf, ymax = Inf),
    fill = background_diff,
    color = background_diff
  ) +
  # Add Differences values
  geom_text(
    # Bold face
    fontface = "bold",
    # Font size
    size = 4,
    # Font Color
    colour = "black",
    # Position
    mapping = 
      aes(
        x = 1.1,
        y = Horse,
        label = 
          # To avoid duplicate values, plot empty text for the first group and
          # plot the difference only for the Ages_18_34 group.
          ifelse(group == "dp",
                 # Value_if_True
                 "",
                 #Value_if_False
                 # If the difference is equal to zero, do not put any signal. 
                 # Otherwise, if Positive, put the + sign on the front.
                 ifelse(cdlt == 0,
                        # Value_if_True:
                        paste0(as.character(round(cdlt,0))),
                        # Value_if_False
                        ifelse(cdlt > 0, 
                               # Value_if_True
                               paste0("+",as.character(round(cdlt,0))),
                               # Value_if_False
                               paste0(as.character(round(cdlt,0)))
                        )
                 )
              )
      )
  ) +
  # Insert Title of Differences
  geom_text(
    # Bold face
    fontface = "bold",
    # Font size
    size = 4,
    # Cor
    colour = "gray",
    # Set text a little above the dots
    nudge_y = 0.6,
    # Position
    mapping = 
      aes(
        x = 1.1,
        y = Horse,
        label = 
          # If Country is Germany, plot values
          ifelse(pos == 1,
                 # Value_if_True
                 "DIFF",
                 #Value_if_False
                 ""
          )
      )
  ) +
  # Plot Title and Axis Labels
  labs(
    title = "Distance Run and Velocity",
    subtitle = paste0(
      "How far and fast are the horses running"
      ),
    x = "",
    y = ""
    ) +
  # Change background, General font size, and other things
  theme(
    # Change font color and text for all text outside geom_text
    text = element_text(color = "#4e4d47", size = 14),
    
    # Country names in bold face
    axis.text.y = element_text(face = "bold"),
    
    # Add space between x axis text and plot 
    axis.text.x = element_text(vjust = -0.75),
    
    # Do not show tick marks
    axis.ticks = element_blank(),
    
    # Delete original legend (keep only the one we created)
    legend.position = "none",
    
    # White background
    panel.background = element_blank(),
    
    # Country (y Axis) Lines
    panel.grid.major.y = element_line(colour = light_gray, size = 1),
    
    # Change Title Font
    plot.title = element_text(face = "bold", size = 16),
    
    # Change Subtitle Font and add some margin
    plot.subtitle = element_text(face = "italic", size = 12,
                                 margin = margin(b = 0.5, unit = "cm"))
  ) 

p