library(dplyr)
library(plotly)

signal_plotly <- function(df, dict, thr_pval = 5 * 10^-8, type = "column") {
  if("GENE" %in% dict$dataset[dict$id %in% df$from]){
    df <- df[!(df$to == "SHBG" & df$dataset == "GENE"), ]
  } else {
    df <- df[!(df$to == "SHBG" & df$dataset == "Others"), ]
  }
  df$p <- df$weight
  df$p[df$p == 0] <- min(df$p[df$p != 0])/2
  df$p <- signif(-log10(df$p), 3)
  df$p[df$p < 1] <- 1
  
  df$pval <- signif(df$weight, 2)
  
  df$shape_group <- df$dataset
  df$shape_group[df$dataset %in% "GENE"] <- df$group[df$dataset %in% "GENE"]

  df <- df[order(tolower(df$shape_group), df$to), ]
  
  # saveRDS(df, "test_plotly_multi.rds")
  
  # df %>% 
  #   plot_ly(hovertext = ~paste(from, " -> ", to, " (", desc, ")",
  #                              "<br><b>Dataset: </b>", dataset, 
  #                              "<br><b>Group: </b>", group, 
  #                              "<br><b>P-value: </b>", pval),
  #           hoverinfo = "text") %>%
  #   #Plot symbols for cyl
  #   add_trace(type = "scatter",
  #             x = ~to, 
  #             y = ~p,
  #             # text = ~car,
  #             symbol = ~as.factor(from),
  #             mode = 'markers',  
  #             legendgroup="from",
  #             marker = list(color = "grey", size = 13)) %>%
  #   #Overlay color for gears
  #   add_trace(type = "scatter",
  #             x = ~to, 
  #             y = ~p,
  #             # text = ~car,
  #             color = ~as.factor(shape_group),
  #             mode = 'markers', 
  #             legendgroup="shape_group", showlegend = FALSE)%>%
  #   layout(hovermode = "x", 
  #          yaxis = list(title = '-log10(P-value)'), 
  #          xaxis = list(title = list(text=NULL), 
  #                       categoryorder = "array", 
  #                       categoryarray = unique(df$to)))
  
  fig <- plot_ly(data = df, x = ~to, y = ~p, color = ~shape_group, symbol =~from,
                 hovertext = ~paste(from, " &#8594; ", to, " (", desc, ")",
                                    "<br><b>Dataset: </b>", dataset, 
                                    "<br><b>Group: </b>", group, 
                                    "<br><b>P-value: </b>", pval),
                 hoverinfo = "text",
                 colors = "Paired",
                 type = 'scatter', mode = 'markers') %>%
    layout(hovermode = "x", 
           yaxis = list(title = '-log10(P-value)'), 
           showlegend = ifelse(sum(df$dataset %in% "GENE") > 0, FALSE, TRUE),
           # legend = list(title=list(text=paste0('<b>', ifelse(sum(df$dataset %in% "GENE") > 0, "Group", "Dataset"), '</b>'))),
           xaxis = list(title = list(text=NULL),
                        categoryorder = "array", 
                        categoryarray = unique(df$to)))
  
  # if(length(unique(df$dataset)) > 1) {
  # saveRDS(df, "df.rds")
  
    df_uniq <- df[!duplicated(df$to), -"from"]

    groups <- table(df_uniq$shape_group)
    # saveRDS(groups, "test_groups.rds")
    print(groups)
    # df_groups <- data.frame(text = names(groups), 
    #                         x0 = c(-0.5, cumsum(c(groups[1:(length(groups) - 1)])) + 0.5),
    #                         x1 = cumsum(groups) + 0.5)
    # df_groups <- as.data.frame(groups)
    df_groups <- data.frame(text = names(groups), 
                            n = as.vector(groups),
                            x0 = cumsum(c(-0.5, groups[1:(length(groups) - 1)])),
                            x1 = cumsum(groups) - 0.5)
    df_groups$x = df_uniq$to[ceiling(df_groups$x0 + (df_groups$x1-df_groups$x0)/2)+1]
    df_groups$xx = (df_groups$x0 + (df_groups$x1-df_groups$x0)/2)
    df_groups$label = gsub(" \\(GO:.+", "", df_groups$text, perl = TRUE)
    
    # saveRDS(df_groups, "test_df_groups.rds")
    shapes <- NULL
    
    for (i in 1:nrow(df_groups)) {
      color = ifelse(i %% 2 == 0, "grey", "white")
      shapes <- c(shapes, list(list(
        type = "rect", opacity = ifelse(i %% 2 == 0, 0.2, 0), 
        fillcolor = color, line = list(color = color), 
        x0 = df_groups$x0[i], x1 = df_groups$x1[i],
        y0 = min(df$p) - 1, y1 = max(df$p) + 1)))
      # fig <- fig %>% add_annotations(showlegend = FALSE, hoverinfo="none",
      #                            textfont = list(color = c('#000000')),
      #                            textposition = "bottom left", textangle = 90,
      #                            showarrow = FALSE,
      #                            text = df_groups$label[i],
      #                            x = df_groups$xx[i], y = max(df$p) + 1)
    }
    fig <- fig %>% layout(shapes = shapes)
    
    # fig <- fig %>%
    #   add_bars(data = df, x = ~to, y = ~y0, type = 'bar',
    #            text = df$group, textposition = 'inside',
    #            # rotate label
    #            textangle = 90,
    #            marker = list(color = 'rgba(158,202,225, 1)',
    #                          line = list(color = 'rgba(8,48,107, 1)', width = 1.5)))
    
  # }
  
  fig
  
  
}
