using DelimitedFiles, LightGraphs, Combinatorics
include("./misc.jl")
include("./graph.jl")



function construct_network_graph(instance_path::String)
    "In construct_network_g $instance_path"
    data = load_matpower(instance_path)
    println("Okay c passé")
    ## Bus load and shunt information
    i_debut, i_fin = find_numarray(1, data)
    checkfor(data, i_debut - 1, "mpc.bus")
    nb_bus = i_fin - i_debut + 1
    index_bus = Dict( data[i + i_debut - 1,1] => i for i=1:nb_bus)
    if index_bus != Dict( i => i for i=1:nb_bus)
        #println("!!! Specific numerotation of buses !!! \n")
    end
    ## Bus generator information
    i_debut, i_fin = find_numarray(i_fin + 1, data)
    checkfor(data, i_debut - 1, "mpc.gen")
    #initialize network g G
    G = SimpleGraph(nb_bus)
    ## Link information
    i_debut, i_fin = find_numarray(i_fin + 1, data)
    checkfor(data, i_debut - 1, "mpc.branch")
    for i=i_debut:i_fin
        if data[i, 11] == 0
        #@warn("link $(data[i,1])⟶$(data[i,2]) breaker out of service !")
        else
            orig = index_bus[data[i,1]]
            dest = index_bus[data[i,2]]
            LightGraphs.add_edge!(G, orig, dest)
        end
    end
    return G
end


function construct_graph_from_cliques(cliques::AbstractVector)
    nb_vertex = maximum([maximum(c) for c in cliques])
    g = SimpleGraph(nb_vertex)
    for clique in cliques
        make_complete!(g, clique)
    end
    return g
end


function construct_metagraph(g::AbstractGraph)
    mg = MetaGraph(g)
    for v in vertices(g)
        set_indexing_prop!(mg, v, :v, v)
    end
    return mg
end


function construct_graph_from_matrix(L)
    n = size(L,1)
    H = MetaGraph(n)
    for i in 1:n
        set_props!(H, i, Dict(:name => "node$i"))
    end
    for i in 1:n
        for j in 1:i
            if L[i,j] != 0
                MetaGraphs.add_edge!(H,i,j)
            end
        end
    end
    return H
end
