

plot_network2 <- function(center_nodes, df_edges, df_nodes, attrs, 
                         colors_group,  shapes,
                         hide_labels = TRUE, 
                         directed = FALSE,
                         node_num_cutoff = 500, 
                         layout = "layout_with_fr"){
  if(nrow(df_edges) > 0){
    draw.data = dataNetwork2(center_nodes, df_edges, df_nodes, attrs, colors_group, shapes, directed)
    df_edges = draw.data[[1]]
    df_nodes = draw.data[[2]]
    legends = draw.data[[3]]
    # print("draw")
    # print(head(df_edges))
    # print(head(df_nodes))
    
    if(hide_labels){
      df_nodes$label <- "    "
      df_nodes$font.size[df_nodes$iscenter == "center"] <- 50
      df_nodes$font.size[df_nodes$iscenter == "other"] <- 30
      df_nodes$font.background <- NA
    }
    
    addEdges = NULL
    if(directed){
      addEdges = attrs$attr_legend_edge
    } 
    
    df_nodes <- df_nodes[!duplicated(df_nodes$id),]
    print("plot_network2")
    print(nrow(df_nodes))
    
    # saveRDS(df_nodes, "test_df_nodes.rds")

    p <- visNetwork(df_nodes, df_edges, width = "100%",height = "100%") %>%
      visLegend(addNodes = legends,
                addEdges = addEdges,
                width = 0.2,
                position = "right",
                useGroups = FALSE,
                zoom = TRUE,
                stepX = 150,
                stepY = 70,
                ncol = 1) # %>%
      # visClusteringByGroup(groups = df_nodes$group,
      #                      label = "Cluster:\n",
      #                      scale_size = TRUE,
      #                      # shape = c(rep("ellipse",length(group.target)),
      #                      #           rep("ellipse",length(group.other))),
      #                      # color = c(rep("#9955FF",length(group.target)),
      #                      #           text.group.color),
      #                      force = FALSE)
    add_attr_network(p, layout)
    
  } else {
    visNetwork(data.frame(), data.frame(), width = "100%",
               main = paste("Try to click some rows in",tagList(icon("table")),"to specify your nodes"))
  }
}




dataNetwork2 <- function(center_nodes, df_edges, df_nodes, attrs, 
                        colors_group, shapes, directed){
  
  df_edges$title <- paste(df_edges$from, "<b> &rarr; </b>", df_edges$to, ": ", signif(df_edges$weight, 3))
  
  df_edges$ends <- apply(df_edges[, c("from", "to")], 1, function(x){
    paste(sort(x), collapse = "|")
  })
  
  if(!directed){
    
    df_edges <- df_edges %>%
      dplyr::group_by(.data$ends) %>%
      dplyr::summarise(from = gsub("\\|.+", "", .data$ends[1], perl = TRUE),
                       to = gsub(".+\\|", "", .data$ends[1], perl = TRUE),
                       length = mean(abs(.data$weight)^(-1.1)*10),
                       title = .data$title[1])
    
  } else {
    
    df_edges$direction = 1
    df_edges$direction[(!df_edges$from %in% center_nodes) & (df_edges$to %in% center_nodes)] = -1
    
    df_edges <- df_edges %>%
      dplyr::group_by(.data$ends) %>%
      dplyr::summarise(from = gsub("\\|.+", "", .data$ends[1], perl = TRUE),
                       to = gsub(".+\\|", "", .data$ends[1], perl = TRUE),
                       length = mean(abs(.data$weight)^(-1.1)*10),
                       title = paste(.data$title, collapse = "<br>"), 
                       direction = sum(.data$direction))
    
    df_edges$arrows <- "to"
    df_edges$arrows[df_edges$direction == -1] <- "from"
    df_edges$arrows[df_edges$direction == 0] <- "from;to"
  }
  
  df_edges$edgetype <- "center-other"
  df_edges$edgetype[df_edges$from %in% center_nodes &
                      df_edges$to %in% center_nodes ] <- "center-center"
  
  if(directed){
    df_edges$edgetype[df_edges$direction == -1] <- "other-center"
    df_edges$edgetype[df_edges$direction == 0] <- "two-way"
  }
  
  # attr_edges
  # edgetype      color.color       width
  # center-center #FEF65C           4
  # center-other  rgba(128,128,128) 2
  # other-center  #26FD8D           2
  # two-way       #FF96EB           4
  df_edges <- left_join(df_edges, attrs$attr_edges, by = "edgetype")
  
  
  
  df_nodes$iscenter <- "other"
  df_nodes$iscenter[df_nodes$id %in% center_nodes] <- "center"
  
  # attr_nodes_center
  # iscenter
  df_nodes <- left_join(df_nodes, attrs$attr_nodes_center, by = "iscenter")
  
  
  
  # colors_group
  # group color.background
  df_nodes <- left_join(df_nodes, colors_group, by = c("type_color" = "group"))
  # df_nodes$color.background[df_nodes$type_color %in% c("GENE", "GO")] <- colors_group$color.background[match(df_nodes$type_color[df_nodes$type_color %in% c("GENE", "GO")], colors_group$group)]
  
  print(colors_group)
  # saveRDS(df_nodes, "test_color_df_nodes.rds")
  
  print('unique(df_nodes$Category[df_nodes$dataset %in% c("GENE", "GO")]))')
  print(unique(df_nodes$Category[df_nodes$dataset %in% c("GENE", "GO")]))
  print(colors_group)
  
  df_nodes$color.highlight.background = 
    df_nodes$color.hover.background = 
    df_nodes$color.border = df_nodes$color.background
  
  df_nodes$font.color = df_nodes$color.background
  df_nodes$font.color[grepl("GO:", df_nodes$id)] = "Black"
  
  # attr_nodes_type:
  # type      shape
  # NLP       ellipse
  # Codified  box
  # attr_nodes_type:
  # type      shape
  # CUI       dot
  # nonCUI    square
  # attrs$attr_nodes_type$shape <- rep(shapes, 2)
  
  # df_nodes <- left_join(df_nodes, shapes, by = "Category")
  # # df_nodes$shape <- "dot"
  # 
  # 
  # 
  # df_nodes$shape[grepl("Group:", df_nodes$id)] <- "box"
  # df_nodes$font.color[grepl("Group:", df_nodes$id)] <- "white"
  
  # df_nodes$shape <- shapes$shape[shapes$Category == "Phenotype"]
  # df_nodes$shape[df_nodes$id %in% center_nodes] <- shapes$shape[shapes$Category == "Center"]
  # df_nodes$shape[df_nodes$dataset %in% "GENE"] <- shapes$shape[shapes$Category == "GENE"]
  # df_nodes$shape[df_nodes$dataset %in% "GO"] <- shapes$shape[shapes$Category == "GO"]
  df_nodes$type_shape[df_nodes$id %in% center_nodes] <- "Center"
  df_nodes <- left_join(df_nodes, shapes, by = c("type_shape" = "type"))
  
  
  legends <- df_nodes[, c("type_color", "type_shape", "shape", "color.background")]
  legends <- legends[!duplicated(legends), ]
  colnames(legends) <- c("label", "label_shape", "shape", "color")
  legends$size <- 10
  legends$font.size <- 10
  legends$font.color <- "black"
  legends <- legends[order(legends$shape, legends$label),]
  
  legends$label[legends$shape == "box"] <- "Group"
  
  print(legends)
  
  # if(length(unique(legends$shape)) > 1){
  #   for (s in unique(attrs$attr_nodes_type$shape)){
  #     if(s %in% legends$shape){
  #       legends <- dplyr::add_row(
  #         legends,
  #         data.frame("label" = attrs$attr_nodes_type$type[match(s, attrs$attr_nodes_type$shape)],
  #                    "shape" = "box",
  #                    "color" = "rgba(0,0,0,0)",
  #                    "size" = 10,
  #                    "font.size" = 20,
  #                    "font.color" = "white"),
  #         .before = match(s, legends$shape)
  #       )
  #     }
  #   }
  # }
  
  
  return(list(df_edges, df_nodes, legends))
}

add_attr_network <- function(p, layout = "layout_with_fr"){
  p %>%
    visNodes(shadow = list(enabled = TRUE, size = 4, x = 3, y = 3)) %>%
    visEdges(physics = FALSE,
             smooth = FALSE,
             hoverWidth = 2.5) %>%
    visOptions(highlightNearest = list(enabled = T,
                                       degree = 1,
                                       hover = FALSE,
                                       hideColor = "rgba(200,200,200,0.2)"),
               collapse = list(enabled = TRUE, keepCoord = TRUE)) %>%
    
    
    
    visInteraction(hover = TRUE) %>%
    visIgraphLayout(layout = layout,
                    physics = FALSE,
                    smooth = FALSE,
                    type = "square") %>%
    visEvents(click = "function(nodes) {
                    Shiny.onInputChange('current_node_id', nodes);
                    ;}") %>%
    visEvents(oncontext = "function(nodes) {
                    Shiny.onInputChange('expand_node_id', nodes);
                    ;}") %>%
    visLayout(randomSeed = 10) 
}
