// GraphTea Project: http://github.com/graphtheorysoftware/GraphTea
// Copyright (C) 2012 Graph Theory Software Foundation: http://GraphTheorySoftware.com
// Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology
// Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/
package graphtea.plugins.commandline.commands;

import graphtea.graph.graph.Edge;
import graphtea.graph.graph.GraphModel;
import graphtea.graph.graph.Vertex;
import graphtea.platform.core.BlackBoard;
import graphtea.platform.lang.CommandAttitude;
import graphtea.platform.parameter.Parameter;
import graphtea.plugins.main.GraphData;

import java.util.HashMap;
/**
 * @author Mohammad Ali Rostami
 */
public class NativeCommands {
    private final BlackBoard bb;
    private final GraphData datas;

    public NativeCommands(BlackBoard bb) {
        this.bb = bb;
        datas = new GraphData(bb);
    }

    private native String homomorph(String graph_format1, String graph_format2);

    @CommandAttitude(name = "ghomomorph", abbreviation = "_ghom", description = "check homomorphism")
    public String ghomomorph(@Parameter(name = "first_graph")GraphModel g1,
                             @Parameter(name = "second_graph")GraphModel g2) {
        String graph1 = "";
        String graph2 = "";
        graph1 += g1.getVerticesCount() + "\n";
        graph2 += g2.getVerticesCount() + "\n";

        HashMap<Integer, Integer> map = new HashMap<>();
        HashMap<Integer, Integer> nmap = new HashMap<>();
        int counter = 0;
        for (Vertex vv : g1) {
            map.put(vv.getId(), counter);
            nmap.put(counter++, vv.getId());
        }

        for (Edge e : g1.getEdges()) {
            graph1 += map.get(e.source.getId()) + " " + map.get(e.target.getId()) + "\n";
        }

        map = new HashMap<>();
        counter = 0;

        for (Vertex vv : g2)
            map.put(vv.getId(), counter++);

        for (Edge e : g2.getEdges()) {
            graph2 += map.get(e.source.getId()) + " " + map.get(e.target.getId()) + "\n";
        }

        String s = homomorph(graph1, graph2);
        double time = Double.parseDouble(s.substring(0, s.indexOf("\n")));
        s = s.substring(s.indexOf("\n") + 1);
        if (s.equals("false")) return "time : " + time + ".\nNo homomorphism exists.";
        String result = "";
        for (String temp : s.trim().split("\\s+")) {
            result = result + nmap.get(Integer.parseInt(temp.substring(0, temp.indexOf("-")))) + "->"
                    + nmap.get(Integer.parseInt(temp.substring(temp.indexOf(">") + 1))) + "\n";
        }

        return "time : " + time + ".\nFounded Homomorphism is:\n" + result;
    }
}
