#!/usr/bin/env python
#
# ExploitGraph.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA

import json
import logging

NETWORKX_MODULE = True

try:
    import networkx
    from networkx.readwrite import json_graph
except ImportError:
    NETWORKX_MODULE = False

log = logging.getLogger("Thug")


class ExploitGraph(object):
    def __init__(self, url):
        self.enabled = NETWORKX_MODULE
        if not self.enabled:
            return

        self.G = networkx.MultiDiGraph(url = url, name = "thug-exploit-graph")

    def add_connection(self, source, destination, method):
        if not self.enabled:
            return

        self.G.add_node(source)
        self.G.add_node(destination)
        self.G.add_edge(source, destination, method = method)

    def draw(self):
        if not self.enabled:
            return None

        G = networkx.convert_node_labels_to_integers(self.G, label_attribute = 'url')
        d = json_graph.node_link_data(G)

        return json.dumps(d)
