# -*- coding: utf-8 -*

def table2xml(keyphrases_table):
    res = "<table>\n"
    for keyphrase in sorted(keyphrases_table.keys()):
        res += '  <keyphrase value="%s">\n' % keyphrase
        for text in sorted(keyphrases_table[keyphrase].keys()):
            res += '    <text name="%s">' % text
            res += '%.3f' % keyphrases_table[keyphrase][text]
            res += '</text>\n'
        res += '  </keyphrase>\n'
    res += "</table>\n"
    return res


def table2csv(keyphrases_table):

    def quote(s):
        return '"' + s.replace('"', "'") + '"'

    keyphrases = sorted(keyphrases_table.keys())
    texts = sorted(keyphrases_table[keyphrases[0]].keys())
    res = "," + ",".join(map(quote, keyphrases)) + "\n"  # Heading
    for text in texts:
        scores = map(lambda score: u"%.3f" % score,
                     [keyphrases_table[keyphrase][text] for keyphrase in keyphrases])
        res += (quote(text) + "," + ",".join(scores) + "\n")
    return res


def graph2edges(graph):
    res = ""
    node_edges = {}
    for edge in graph["edges"]:
        source_label = graph["nodes"][edge["source"]]["label"]
        target_label = graph["nodes"][edge["target"]]["label"]
        if source_label not in node_edges:
            node_edges[source_label] = []
        node_edges[source_label].append(target_label)
    for node in node_edges:
        res += "%s -> %s\n" % (node, ", ".join(node_edges[node]))
    return res


def graph2gml(graph):
    res = "graph\n[\n"
    i = 0
    for node in graph["nodes"]:
        res += '  node\n  [\n    id %i\n    label "%s"\n  ]\n' % (node["id"], node["label"])
        i += 1
    for edge in graph["edges"]:
        res += '  edge\n  [\n    source %i\n    target %i\n  ]\n' % (edge["source"],
                                                                     edge["target"])
    res += "]\n"
    return res

@@ -1491,18 +1491,8 @@
 %5Cn%22%0A
-    i = 0%0A
     
@@ -1534,16 +1534,17 @@
  res += 
+(
 '  node%5C
@@ -1584,16 +1584,32 @@
   %5D%5Cn' %25
+%0A               
  (node%5B%22
@@ -1632,23 +1632,9 @@
 l%22%5D)
-%0A        i += 1
+)
 %0A   
@@ -1677,16 +1677,17 @@
  res += 
+(
 '  edge%5C
@@ -1728,115 +1728,102 @@
 %5Cn  
-%5D%5Cn' %25 (edge%5B%22source%22%5D,%0A                                                                     edge%5B%22target%22%5D
+  confidence %25.2f  %5D%5Cn' %25%0A                (edge%5B%22source%22%5D, edge%5B%22target%22%5D, edge%5B%22confidence%22%5D)
 )%0A  

Return edge confidence in GML