import os
import networkx as nx
import genFunctions as genF
from ctypes import cdll
labelg = cdll.LoadLibrary('../gen_c/nauty/labelg')


def expandGraph(graph, line):
    elements = line.split()
    elements.pop(1)
    first = elements.pop(0)
    for second in elements:
        if(int(second) > int(first)):
            graph.add_edge(int(first),int(second))


def insertGraph(container, canonicCont, graph):
    size = graph.number_of_nodes()
    canonic = genF.returnSimpleCanonic(graph)
    if(canonic not in canonicCont[(size//2) - 1]):
        canonicCont[(size // 2) - 1].append(canonic)
        container[(size//2) - 1].append(graph)


def generate(verticeNum):

    graphContainer = [[] for i in range(verticeNum//2)]
    graphCanonicForm = [[] for i in range(verticeNum // 2)]

    g = nx.MultiGraph()
    g.add_edges_from([(1,2),(1,2),(1,2)])

    graphContainer[0].append(g)

    for i in range (4, verticeNum, 2):
        cmd = 'cd ../genreg-code-3-trunk && exec ./genreg '+str(i)+' 3 -a'
        os.system(cmd)  # returns the exit status

    for i in range(4, verticeNum, 2):
        read = False
        name = "../genreg-code-3-trunk/graphs/" + str(i).zfill(2) + "_3_3.asc"
        with open(name, 'r') as f:
            for line in f:

                if("Graph" in line):
                    read = True
                    currentGraph = nx.MultiGraph()
                if ("Taillenweite" in line):
                    insertGraph(graphContainer,graphCanonicForm, currentGraph)
                    read = False
                if(line != "\n" and read):
                    expandGraph(currentGraph, line)

    for i in range(0, verticeNum//2 - 1):
        for gr in graphContainer[i]:
            for u, v, x in gr.edges:
                newGr = genF.addTwoNodesOnEdge(gr, (u, v))
                insertGraph(graphContainer,graphCanonicForm, newGr)


    return graphContainer
