library("tidyverse")
library("gridExtra")

pdf(NULL)

# Load data
data=read_csv("wakeup.csv")    
yorder=str_sort(unique(data$node),numeric=TRUE)
data=data%>%mutate(node=factor(node,levels=yorder))

# Load hint
hint=read_csv("hint.csv")

# Load hint forward
hint_fw=read_csv("hint_fw.csv")

# Load data
data_rcv=read_csv("data.csv")


# Configure axis
ts_range=seq(0, 24)*3600
ts_labels=ts_range/3600

# Plot
p1=ggplot(data,aes(x=wakets,y=node)) + geom_hline(aes(yintercept=node),color="grey",size=3)
if(NROW(hint)!=0){
    p1=p1+geom_vline(data=hint,aes(xintercept=wakets,color="Hint slots"),show.legend = FALSE,linetype="longdash",size=0.3)
}
p1=p1+geom_linerange(aes(xmin=wakets,xmax=sleepts),size=10)
if(NROW(hint)!=0){
    p1=p1+geom_linerange(data=hint,aes(xmin=wakets,xmax=wakets+duration,color="Hint slots"),size=10)
}
if(NROW(data_rcv)!=0){
    p1=p1+geom_point(data=data_rcv,aes(x=ts,color="Data received"),shape=18,size=4)
}
if(NROW(hint)!=0){
    p1=p1+geom_point(data=hint,aes(x=rcvat,color="Hint received"),shape=18,size=3)
}
if(NROW(hint_fw)!=0){
    p1=p1+geom_point(data=hint_fw,aes(x=ts,color="Hint Forwarded"),shape=18,size=2)
}
p1=p1+
    xlab("Time (hours)")+ylab("Node")+
    scale_x_continuous(breaks = ts_range, labels=ts_labels,expand = c(0, 0))+
    scale_colour_manual(name="Legend",values=c("Hint slots"="blue","Data received"="red","Hint received"="green","Hint Forwarded"="purple"))+
    theme(panel.grid.major.x = element_line(size = 1.2),panel.grid.major.y = element_blank(),panel.grid.minor = element_blank())

stats=data%>%group_by(node)%>%summarise(n=n())%>%mutate(nwakeup=n-24)

p2=ggplot(stats,aes(x=node,y=nwakeup))+
    geom_bar(stat="identity")+xlab("Node")+ylab("Extra wake up count")+ylim(0,10)+
    scale_y_continuous(breaks = seq(0,10))

stats2=tibble(
    metric=c("Hint Received","Hint Forwarded","Data Received"),
    count=c(NROW(hint),NROW(hint_fw),NROW(data_rcv))
)

p3=ggplot(stats2,aes(x=metric,y=count))+
    geom_bar(stat="identity")+xlab("Metric")+ylab("Count")+ylim(0,20)


p=grid.arrange(p1,p2,p3,heights=c(10,5,5))
ggsave(plot=p,"schedule.png",dpi=300,width = 10,height=10)
