import org.apache.commons.math3.fitting.PolynomialCurveFitter;
import org.apache.commons.math3.fitting.WeightedObservedPoints;
import org.graphstream.graph.Node;
import org.graphstream.graph.Graph;
import org.graphstream.graph.implementations.DefaultGraph;
import org.graphstream.stream.file.FileSource;
import org.graphstream.stream.file.FileSourceDGS;
import org.graphstream.ui.graphicGraph.GraphPosLengthUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;

/**
 * The goal of this class is to compute the correlation Dimension of the graph store in a dgs file
 *
 */
public class CorrelationDimension {

	/**
	 * The goal of the function is to add to the input argument graph g all the nodes present in the dgs file at the
	 * argument path.
	 *
	 * @param g graph to which we want to add the nodes
	 * @param path the path to the dgs file where the graph data is store
	 */
	public void add_node_to_graph_from_dgs_file(Graph g, String path, int nb_noeuds) throws IOException {
		FileSource fs = new FileSourceDGS();

		fs.addSink(g);
		int i = 0;
		try {
			fs.begin(path);
			while (fs.nextEvents() && i <= nb_noeuds) {
				i = i + 1;
			}
		} catch( IOException e) {
			throw  new IOException(e);
		}
	}

	/**
	 * The goal of this function is to find the max and the value of all the x coordinates and the same for the y
	 * coordinates of the graph g
	 * @param g the graph in which we are searching the min and max coordinates
	 * @return a Hashtable to associate the values to understandable key :
	 * x_min = the minimal x coordinate
	 * x_max = the maximal x coordinate
	 * y_min = the y min coordinate
	 * y_max = the y max coordinate
	 */
	public Hashtable<String, Float> get_min_max_coord(Graph g) {
		Hashtable<String, Float> extreme_coord = new Hashtable<>();
		extreme_coord.put("x_min", Float.MAX_VALUE);
		extreme_coord.put("x_max", Float.MIN_VALUE);
		extreme_coord.put("y_min", Float.MAX_VALUE);
		extreme_coord.put("y_max", Float.MIN_VALUE);
		g.nodes().forEachOrdered((n) -> {
			double[] coords = GraphPosLengthUtils.nodePosition(n);
			if (coords[0] > extreme_coord.get("x_max")) {
				extreme_coord.put("x_max", (float) coords[0]);
			}
			if (coords[0] > extreme_coord.get("x_min")) {
				extreme_coord.put("x_max", (float) coords[0]);
			}
			if (coords[1] > extreme_coord.get("y_max")) {
				extreme_coord.put("y_max", (float) coords[0]);
			}
			if (coords[1] > extreme_coord.get("y_min")) {
				extreme_coord.put("y_max", (float) coords[0]);
			}
		});
		return extreme_coord;
	}

	/**
	 * The goal of this function is to move the graph to the origine with the min values. We are also going to rescale
	 * the nodes of the graph wit the attribut scale
	 *
	 * @param extreme_coord the extrem_values of the graph
	 * @param scale the scale value to use to rescale the graph
	 * @param g the graph in which we are going to move the nodes
	 */
	public void move_graph(Hashtable <String, Float>extreme_coord, double scale, Graph g) {
		g.nodes().forEach((n) -> {
			double[] coords = GraphPosLengthUtils.nodePosition(n);
			coords[0] = (coords[0] - extreme_coord.get("x_min")) * scale;
			coords[1] = (coords[1] - extreme_coord.get("y_min")) * scale;
			n.setAttribute("xy", coords[0], coords[1]);
		});
	}

	/**
	 * The goal of this function is to compute the correlation of the graph by changing the size of the boxes. The size
	 * of the boxes will begin from min_size_box to max_size_box. It compute the correlation for each size of box possible
	 * and register the result in an ArrayList.
	 *
	 * @param g
	 * @param extSize
	 */
	public ArrayList<double[]> compute_correlation_dimension(Graph g, double[] extSize) {
		int nc = g.getNodeCount();
		Collection<Node> nodes = new ArrayList<>();
		g.nodes().forEach(nodes::add);
		ArrayList<double[]> distributionLog = new ArrayList<>();
		for ( double sizeBox = extSize[0] ; sizeBox <= extSize [1] ; sizeBox = sizeBox + extSize[0] ) {
			double sum = this.get_number_of_nodes_in_area(nodes, sizeBox);
			double e = ( 2.0 / ( nc * (nc -1) ) ) * sum ;
			e = (e <= 0) ? 0.00001 : e;
			distributionLog.add(new double[] { 	Math.log(sizeBox) ,  Math.log(e) });
			System.out.println("size box : " + sizeBox);
		}
		return distributionLog;
	}

	/**
	 * This function is computing for each nodes of the graph the number of nodes present in their area of size sizeBox
	 *
	 * @param nodes all the nodes of the graph
	 * @param sizeBox the size of the area section where we are computing the number of nodes
	 * @return the number of nodes present in the area of each nodes
	 */
	private double get_number_of_nodes_in_area(Collection<Node> nodes, double sizeBox) {
		int[] sum = {-1};
		nodes.parallelStream().forEach((n0) -> {
			double[] n0_coord = GraphPosLengthUtils.nodePosition(n0);
			for ( Node n1 : nodes ) {
				double[] n1_coord = GraphPosLengthUtils.nodePosition(n1);
				if (Math.hypot(n0_coord[0] - n1_coord[0], n0_coord[1] - n1_coord[1])  < sizeBox ){
					sum[0] = sum[0] + 1 ;
				}
			}
		});
		return sum[0];
	}

	/**
	 * This function is calculating the coefficient of the data passing thought the argument as a Polynomial Curve
	 * Fitter.
	 *
	 * @param distributionLog The distribution of data use in the PolynomialCurveFitter. The data are store in an
	 *                        ArrayList as :
	 *                        - 0 => x
	 *                        - 1 => y
	 * @return
	 */
	public double[]  getFractalDimension_information(ArrayList<double[]> distributionLog) {
		WeightedObservedPoints obs = new WeightedObservedPoints();
		for ( double[] vals : distributionLog)
			obs.add(vals[0], vals[1]);

		return PolynomialCurveFitter.create(1).fit(obs.toList()) ;
	}

	public static void main(String... args) {
		String path = args[0];
		int nb_noeuds = Integer.parseInt(args[1]);
		System.out.println("path : " + path);
		if (path.endsWith("dgs")) {
			Graph g = new DefaultGraph("graph_test");
			CorrelationDimension correlationDimension = new CorrelationDimension();
			try {
				correlationDimension.add_node_to_graph_from_dgs_file(g, path, nb_noeuds);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			System.out.println("nombre de noeud : " + g.getNodeCount());
			Hashtable<String, Float> extreme_coord = correlationDimension.get_min_max_coord(g);
			System.out.println("xmin : " + extreme_coord.get("x_min") + " x_max : " + extreme_coord.get("x_max")
					+ "  y_min : " + extreme_coord.get("y_min") + "  y_max : " + extreme_coord.get("y_max"));
			extreme_coord.put("x_max", extreme_coord.get("x_max") - extreme_coord.get("x_min"));
			extreme_coord.put("y_max", extreme_coord.get("y_max") - extreme_coord.get("y_min"));
			System.out.println("déplacement vers origine xmin : " + extreme_coord.get("x_min") + " x_max : " +
					extreme_coord.get("x_max") + "  y_min : " + extreme_coord.get("y_min") + "  y_max : " +
					extreme_coord.get("y_max"));

			int[] size_space = {1000, 1000};
			double maxSize = Arrays.stream(size_space).min().getAsInt();
			double delta = 0.001;
			double scale = maxSize / Math.max(extreme_coord.get("x_max"), extreme_coord.get("y_max")) * (1 - delta);
			correlationDimension.move_graph(extreme_coord, scale, g);
			double[] extSizeBox = {1, maxSize};
			ArrayList<double[]> distributionLog = correlationDimension.compute_correlation_dimension(g, extSizeBox);
			double[] informations = correlationDimension.getFractalDimension_information(distributionLog);
			for (double info : informations) {
				System.out.println("info : " + info);
			}
		}
	}
}
