import angr
import argparse
from angrutils import *
from os import remove
import sys

# imports for converting dot graph to json graph
import networkx as nx
from networkx.readwrite import json_graph


def generateCFG(binary, analysisType = 'Fast'):
    # Create the angr project for the binary
    project = angr.Project(binary, auto_load_libs = False)

    # Create the Control Flow Graph in Fast or Accurate mode.
    if (analysisType == 'Fast'):
        cfg = project.analyses.CFG()
    elif (analysisType == 'Accurate'):#
        cfg = project.analyses.CFGAccurate()
    else:
        return

    # output the cfg in dot format
    outputFileName = binary
    plot_cfg(cfg, outputFileName, asminst=True, remove_imports=True, remove_path_terminator=True, format='dot')

    # convert the output graph from angr to json format
    graph_json = _dot_to_json(outputFileName + '.dot')

    # delete the dot file generated by angrutils plot_cfg
    remove(outputFileName + '.dot')

    return graph_json



def _dot_to_json(dotGraph):
    dot_graph = nx.drawing.nx_pydot.read_dot(dotGraph)
    return json_graph.node_link_data(dot_graph)
import angr
from angrutils import *
from os import remove

# imports for converting dot graph to json graph
import networkx as nx
from networkx.readwrite import json_graph


def generateCFG(binary, analysisType = 'Fast'):
    # Create the angr project for the binary
    project = angr.Project(binary, auto_load_libs = False)

    # Create the Control Flow Graph in Fast or Accurate mode.
    if (analysisType == 'Fast'):
        cfg = project.analyses.CFG()
    elif (analysisType == 'Accurate'):#
        cfg = project.analyses.CFGAccurate()
    else:
        return

    # output the cfg in dot format
    outputFileName = binary
    plot_cfg(cfg, outputFileName, asminst=True, remove_imports=True, remove_path_terminator=True, format='dot')

    # convert the output graph from angr to json format
    graph_json = _dot_to_json(outputFileName + '.dot')

    # delete the dot file generated by angrutils plot_cfg
    remove(outputFileName + '.dot')

    return graph_json



def _dot_to_json(dotGraph):
    dot_graph = nx.drawing.nx_pydot.read_dot(dotGraph)
    return json_graph.node_link_data(dot_graph)
remove unused imports