library(ggplot2)
library(cowplot)

signals = read.csv("./signals.csv")
states = read.csv("./states.csv")
events = read.csv("./events.csv")

events_expanded <- merge(signals,events,by="time", all=TRUE)

point_size <- 0.05

events <- ggplot(data=events_expanded , aes(x=time, y=Event, group=fsa)) +
  geom_point(na.rm = FALSE, size = point_size) +
  ylab("Event") + 
  xlab("Time (s)") + 
  scale_y_discrete("Event", labels = waiver(), limits=c("force>100", "up>0.5")) +
  theme(axis.title.y=element_text(vjust=0))

states <- ggplot(data=states , aes(x=time, y=value, group=fsa)) +
  geom_point(size = point_size) +
  ylab("State") + 
  xlab("Time (s)") + 
  scale_y_discrete("State", labels = waiver()) +
  theme(axis.title.y=element_text(vjust=0))

up_data = signals[which(signals$signal == "s_powerwindow_environment_up"), ]

up <- ggplot(data=up_data , aes(x=time, y=value, group=signal)) +
  #geom_point(size = point_size) +
  geom_line(size=point_size/2) + 
  ylab("Up") +
  xlab("Time (s)") +
  theme(axis.title.y=element_text(vjust=0))

force_data = signals[which(signals$signal == "s_powerwindow_environment_force"), ]

force <- ggplot(data=force_data , aes(x=time, y=value, group=signal)) +
  #geom_point(size = point_size) +
  geom_line(size=point_size/2) + 
  ylab("Force") +
  xlab("Time (s)") +
  theme(axis.title.y=element_text(vjust=0))


position_data = signals[which(signals$signal == "s_powerwindow_plant_position"), ]

position <- ggplot(data=position_data , aes(x=time, y=value, group=signal)) +
        geom_point(size = point_size) +
        ylab("Position ") + 
        xlab("Time (s)") +
        theme(axis.title.y=element_text(vjust=0))

nrow <- 5
ncol <- 1

multiplot <- plot_grid(up, force, events, states, position , nrow = nrow, ncol = ncol, align = "v")
multiplot_pf <- plot_grid(force, position , nrow = 1, ncol = 2, align = "h")

save_plot("plots.pdf", multiplot, nrow = nrow, ncol = ncol, base_aspect_ratio = 1.0)
save_plot("plots_pf_pw.pdf", multiplot, nrow = 1, ncol = 2, base_aspect_ratio = 1.0)

