package metric.utils;

import java.io.InputStream;

import org.graphstream.algorithm.generator.BarabasiAlbertGenerator;
import org.graphstream.algorithm.generator.Generator;
import org.graphstream.algorithm.generator.RandomGenerator;
import org.graphstream.graph.Graph;
import org.graphstream.graph.implementations.SingleGraph;
import org.graphstream.stream.file.FileSource;

/**
 * Graph utilities.
 * 
 * @author Yoann Eichelberger
 */
public final class GraphUtils {

    public static Graph readResource(String id, String path, FileSource source) {
        Graph g = new SingleGraph(id);
        try (InputStream is = GraphUtils.class.getClassLoader().getResourceAsStream(path)) {
            source.addSink(g);
            source.readAll(is);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            source.removeSink(g);
        }
        return g;
    }

    public static Graph randomGen(int nodeCount, double averageDegree) {
        Graph graph = new SingleGraph("Random");
        Generator gen = new RandomGenerator((int) Math.round(averageDegree));
        gen.addSink(graph);
        gen.begin();
        System.out.printf("Generate %s...%n", graph.getId());
        for (int i = 0; i < nodeCount; i++) {
            gen.nextEvents();
        }
        System.out.println("done");
        gen.end();
        return graph;
    }

    public static Graph randomPreferencielGraph(int nodeCount, double averageDegree) {
        Graph graph = new SingleGraph("Preferential");
        Generator gen = new BarabasiAlbertGenerator((int) Math.round(averageDegree));
        gen.addSink(graph); 
        gen.begin();
        System.out.printf("Generate %s...", graph.getId());
        for(int i = 0; i < nodeCount; i++) {
            gen.nextEvents();
        }
        System.out.println("done");
        gen.end();
        return graph;
    }
}