package iwocs;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;

import org.graphstream.algorithm.Toolkit;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.SingleGraph;
import org.graphstream.stream.file.FileSource;
import org.graphstream.stream.file.FileSourceEdge;

public class App {
  public static void main(String[] args) {
    Graph g = getNerdsGraph();

    int nb_nodes = g.getNodeCount();
    int nb_links = g.getEdgeCount();

    System.out.format("N: %d\nL: %d\n<k>: %.3f\n<C>: %.3f\nConnected: %b\n",
      nb_nodes,
      nb_links,
      Toolkit.averageDegree(g),
      Toolkit.averageClusteringCoefficient(g),
      Toolkit.isConnected(g)
    );

    exportDegreeDistribution(g, "./data/distrib", true);
  }

  public static void exportDegreeDistribution(Graph g, String destFile, boolean normalized) {
    int[] degreesDistribution = Toolkit.degreeDistribution(g);
    double[] convertedDistribution = new double[degreesDistribution.length];
  
    for(int i=0; i < degreesDistribution.length; i++)
      convertedDistribution[i] = normalized ? 
        (double)degreesDistribution[i] / g.getNodeCount() :
        (double)degreesDistribution[i];

    try {
      BufferedWriter w = new BufferedWriter(new FileWriter(new File(destFile)));

      for(int i=0; i < convertedDistribution.length; i++)
        if(convertedDistribution[i] != 0)
          w.write(String.format("%d\t%f\n", i, convertedDistribution[i]));

      w.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public static Graph getNerdsGraph() {
    Graph g = new SingleGraph("nerds");
    
    FileSource fs = new FileSourceEdge();

    fs.addSink(g);

    try {
      InputStream stream = App.class.getClassLoader().getResourceAsStream("nerds.txt");
      fs.readAll(stream);
    } catch (IOException e) {
      e.printStackTrace();
    }

    return g;
  }
}