---
title: "Analyzing log file"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: 
    vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(alluvial)
library(magrittr) # for %>%
library(dplyr) # for using group_by
library(stringr) # for use str_sub
library(DT)
library(plotly) # for heatmap
```

```{r echo=FALSE}
## FUNCTIONS *********************
## *******************************
Calculate.Hours<-function(x){
  # Calculate records by hour
  tHours<-table(x)
  nHours<-c("00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23")
  Hours<-c(rep(0,24))
  names(Hours)<-nHours
  for (i in c(1:dim(tHours))){
    Hours[as.numeric(names(tHours[i]))+1]<-tHours[i]
  }
  return(Hours)
}

# Clock plot function
clock.plot <- function (x, col = rainbow(n), ...) {
  # addapting from https://www.r-graph-gallery.com/49-clock-plot/
  if( min(x)<0 ) x <- x - min(x)
  if( max(x)>1 ) x <- x/max(x)
  n <- length(x)
  if(is.null(names(x))) names(x) <- 0:(n-1)
  m <- 1.05
  plot(0, type = 'n', xlim = c(-m,m), ylim = c(-m,m), axes = F, xlab = '', ylab = '', ...)
  a <- pi/2 - 2*pi/200*0:200
  polygon( cos(a), sin(a) )
  v <- .02
  a <- pi/2 - 2*pi/n*0:n
  segments( (1+v)*cos(a), (1+v)*sin(a), (1-v)*cos(a), (1-v)*sin(a) )
  segments( cos(a), sin(a),0, 0, col = 'light grey', lty = 3) 
  ca <- -2*pi/n*(0:50)/50
  for (i in 1:n) {
    a <- pi/2 - 2*pi/n*(i-1)
    b <- pi/2 - 2*pi/n*i
    polygon( c(0, x[i]*cos(a+ca), 0), c(0, x[i]*sin(a+ca), 0), col=col[i] )
    v <- .1
    text((1+v)*cos(a), (1+v)*sin(a), names(x)[i])
  }
}


```

```{r}
# Read data

## ************************
# Read log file
# DirFiles<-list.files(getwd(),"csv")
# Read users file
#Users<-read.csv2("Users.csv", header = T, encoding="UTF-8", stringsAsFactors = F)

# LogFile<-read.csv(DirFiles[1], header = T, encoding="UTF-8", stringsAsFactors = F)
# names(LogFile)<-c("DataTime","Nom", "User", "Context","Component", "Event","Description","Origin","Dir.IP")
# LogFile$Data<-as.Date(substr(LogFile$DataTime,1,10), "%d/%m/%Y")

# clean adms, and teachers

# LogFile<-LogFile[LogFile$Nom!="traspaso",]
# LogFile<-LogFile[LogFile$Nom!="-",]
# LogFile<-LogFile[LogFile$Nom!="Admin Aula Global",]

# LogFile$record<-1

# course start at 2019-01-28
# LogFile<-LogFile[LogFile$Data>as.Date("28/01/2019","%d/%m/%Y"),]
# LogFile$Hour<-substr(str_sub(LogFile$DataTime, start= -5),1,2)

# put day o the week
# LogFile$WeekDay<-weekdays(LogFile$Data)
# LogFile$WeekDay<-factor(LogFile$WeekDay, levels=c("lunes" ,"martes", "miércoles" ,"jueves","viernes" ,"sábado" ,"domingo" ), labels = c("Mo","Tu","We","Th","Fr","Sa","Su"))

# calculate net
# UC3m<-substr(LogFile$Dir.IP,1,8)
# IP_UC3m<-UC3m=="163.117."
# LogFile$Net<-factor(IP_UC3m, levels=c(T,F), labels=c("Net_UC3m","Others"))

# LogFile<-LogFile[, c(10,2,4,5,6,9,12,13,14,11)]

# NomAlum<-unique(LogFile$Nom)
# NumAlum<-length(unique(LogFile$Nom))
# alum<-paste0("Alum_",c(1:NumAlum))
# LogFile$Nom<-factor(LogFile$Nom,levels=NomAlum, labels=alum)

```





Select Data
===================================== 

Column {.sidebar}
-----------------------------------------------------------------------

Select a file:

```{r}
# This code was adapted from -->  https://shiny.rstudio.com/gallery/file-upload.html


      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                         "text/comma-separated-values,text/plain",
                         ".csv"))

 # Input: Checkbox if file has header ----
checkboxInput("header", "Header", TRUE)

 # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ",")

# Input: Select quotes ----
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"')



 dataf <-reactive({ 
    read.csv(input$file1$datapath,
                 header = input$header,
                 sep = input$sep,
                 quote = input$quote,
                  encoding = "UTF-8",
                  stringsAsFactors = F)
  })

 #actionButton("tryButton", "Treat the file")

 dataf2<-reactive({
    LogFile<-dataf()
    names(LogFile)<-c("DataTime","Nom", "User", "Context","Component", "Event","Description","Origin","Dir.IP")
    LogFile$Data<-as.Date(substr(LogFile$DataTime,1,10), "%d/%m/%Y")
    LogFile$record<-1
    # course start at 2019-01-28
    LogFile<-LogFile[LogFile$Data>as.Date("28/01/2019","%d/%m/%Y"),]
    LogFile$Hour<-substr(str_sub(LogFile$DataTime, start= -5),1,2)
    # put day o the week
    LogFile$WeekDay<-weekdays(LogFile$Data)
    LogFile$WeekDay<-factor(LogFile$WeekDay, levels=c("lunes" ,"martes", "miércoles" ,"jueves","viernes" ,"sábado" ,"domingo" ), labels = c("Mo","Tu","We","Th","Fr","Sa","Su"))
    # calculate net
    UC3m<-substr(LogFile$Dir.IP,1,8)
    IP_UC3m<-UC3m=="163.117."
    LogFile$Net<-factor(IP_UC3m, levels=c(T,F), labels=c("Net_UC3m","Others"))
    LogFile<-LogFile[, c(10,2,4,5,6,9,12,13,14,11)]
    return(LogFile)
 })
   
        
```


Column
--------------------------

### Data Table

```{r}
renderDT({
    if (is.null(input$file1)){
    return(NULL)
  }else{
    dataf()
  } 
})


```

### Data Table

```{r}

renderDT({
  if (is.null(input$file1)){
    return(NULL)
  }else{
    dataf2()
  } 
})

```

Shiny
===================================== 

Column {.sidebar}
-----------------------------------------------------------------------

Selection of parameters to filter:

```{r}
selectInput("n_weekday", label = "Select a Weekday:",
            choices = c("**ALL","Mo","Tu","We","Th","Fr", "Sa", "Su"), selected = "**ALL")

  LogFile.F <- reactive({
 # conditions
  Cond1<-input$n_weekday
  d1<-dataf2()
  if ((Cond1)=="**ALL") {
     d1<-d1[d1$WeekDay!=Cond1,]
  } else{
     d1<-d1[d1$WeekDay==Cond1,]
  }
  })

```

Column
--------------------------

### Clock


```{r}
renderPlot({
  if (is.null(input$file1)){
    return(NULL)
  }else{
    dd<-LogFile.F()
    cp<-clock.plot(Calculate.Hours(dd$Hour), main = "Clicks Students by  Hours")
    print(cp)
  } 
})  
```

### Number of Students

```{r}
renderValueBox({
    if (is.null(input$file1)){
    return(NULL)
  }else{
    dd<-LogFile.F()
NumsStudents = length(unique(dd$Nom))
valueBox(NumsStudents, icon = "fa-users", color="primary")
  }  
})

```


Column
--------------------------

### Bars


```{r}
renderPlot({
    if (is.null(input$file1)){
    return(NULL)
  }else{
    dd<-LogFile.F()
  bp<-ggplot(dd, aes(fill=Net, y=record, x=Hour)) + 
    geom_bar( stat="identity")
  print(bp)
  }  
})  
```

### Table


```{r}
renderTable({
    if (is.null(input$file1)){
    return(NULL)
  }else{
  dd<-LogFile.F()
  table(dd$Hour,dd$Net)
  }
})  
```

Column
--------------------------

### Table


```{r}
renderPrint({
  if (is.null(input$file1)){
    return(NULL)
  }else{
      dd<-LogFile.F()
      table(dd$Hour, dd$Net)
  }

})  
```

### Net_UC3m (% of use)

```{r}
renderGauge({ 
    if (is.null(input$file1)){
    return(NULL)
  }else{
    dd<-LogFile.F()
    dd1<-round(sum(dd$Net=="Net_UC3m")/sum(table(dd$Net))*100,2)
  gauge(dd1, min = 0, max = 100, symbol = '%', gaugeSectors(
  success = c(67, 100), warning = c(34, 66), danger = c(0, 33) )) 
  }
  })
```

