#TODO gen colorables with c prog, infalte with dual edges,, ?? check isomorphism, save result

import networkx as nx
import copy
import matplotlib.pyplot as plt
import sys
import os
import networkx as nx
import genFunctions as genF

from ctypes import cdll

#gengraph = cdll.LoadLibrary('../genreg-code-3-trunk/genreg.so')
#cd /c && exec /a/helloworld
#cmd = 'cd ../genreg-code-3-trunk && exec ./genreg 6 4 -a'
#os.system(cmd) # returns the exit status
#gengraph.generate()
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 inserGraph(container, canonCheck, graph):
    testGraph = nx.Graph()
    testGraph.add_edges_from(graph.edges)


def generate(verticeNum):

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

    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
        descrBegin = 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):
                    #print("read")
                    read = True
                    currentGraph = nx.MultiGraph()
                if ("Taillenweite" in line):
                    #print("stop read")
                    graphContainer[(i//2) - 1].append(currentGraph)
                    read = False
                    #print(currentGraph.edges)
                if(line != "\n" and read):
                    #print("expand " + str(line))
                    expandGraph(currentGraph, line)

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

    print("$$$$$$$$$$$$$$$")

    for container in graphContainer:
        print("size: "+str(len(container)))
        for gr in container:
            a = 2
            #print(gr.edges)

def returnSimpleCanonic(graph):
    testGraph = nx.Graph()
    testGraph.add_edges_from(graph.edges())
    gr6format = (nx.to_graph6_bytes(testGraph, header=False)).decode()

    with open('../gen_c/nauty/canon_input', 'w') as fileIn:
        fileIn.write(gr6format)

    cmd = 'cd ../gen_c/nauty && exec ./labelg canon_input canon_output'
    os.system(cmd)  # returns the exit status

    with open('../gen_c/nauty/canon_output', 'r') as fileOut:
        output = fileOut.readline()

    return output





#generate(8)

tgr = nx.MultiGraph()
tgr.add_edges_from([(1,1),(0,2),(1,3),(2,3),(1,2),(1,4),(1,5)])
print(returnSimpleCanonic(tgr))

#def generateGraphs