package tp;

import java.io.IOException;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

import org.graphstream.graph.Edge;
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.FileSourceDGS;

public class TestMaxFlow {

  public static void main(String[] args) {
    Graph g = new SingleGraph("test");
    g.addAttribute("ui.antialias");
    g.addAttribute("ui.quality");

    FileSource fs = new FileSourceDGS();
    fs.addSink(g);

    try {
      InputStream is = TestMaxFlow.class.getClassLoader().getResourceAsStream("graph.dgs");
      fs.readAll(is);
    } catch (IOException e) {
      e.printStackTrace();
    }

    g.forEach(n -> n.setAttribute("ui.label", n.getId()));

    MaxFlow mf = new MaxFlow();
    mf.setCapacityAttribute("c");
    mf.init(g);
    mf.setSource(g.getNode("A"));
    mf.setSink(g.getNode("I"));

    mf.compute();

    System.out.println(mf.getFlow());

    for (Edge e : g.getEachEdge()) {
      double flow = mf.getFlow(e);
      double cap = mf.getCapacity(e);
      if (flow > 0)
        e.addAttribute("ui.label", "" + flow);
      if (cap == flow)
        e.addAttribute("ui.style", "fill-color: red;");
    }

    Set<Node> toCut = new HashSet<>(g.getNodeSet());
    toCut.remove(g.getNode("I"));

    Set<Set<Node>> toCutPowerSet = FlowUtils.powerSet(toCut);

    double minC = FlowUtils
        .minCapacity(toCutPowerSet.stream().map(s -> FlowUtils.cut(s)).collect(Collectors.toSet()));
    System.out.printf("Min capacity : %.0f\n", minC);

    g.display(false);
  }

}
