package org.studiorailgun.knowledge;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;

import org.studiorailgun.Globals;

/**
 * Exports a web as a set of CSVs
 */
public class CSVExport {

    /**
     * Path for the export dir
     */
    static final String EXPORT_DIR = "./temp/";

    /**
     * Ending for the node file
     */
    static final String NODE_FILE_END = "_nodes.csv";

    /**
     * Ending for the edge file
     */
    static final String EDGE_FILE_END = "_edges.csv";
    
    /**
     * Exports a web as a pair of CSVs
     * @param name The name of the CSVs
     */
    public static void export(String name){

        
        //make sure the export dir exists
        try {
            Files.createDirectories(new File(EXPORT_DIR).toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }


        //write the nodes
        try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(EXPORT_DIR + name + NODE_FILE_END))))) {
            //header
            writer.println("\"id\",\"label\",\"interval\"");
            //all nodes
            for(Node node : Globals.web.getNodes()){
                writer.println(node.getId() + ",\"" + node.getName() + "\",");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



        //write the edges
        try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(EXPORT_DIR + name + EDGE_FILE_END))))) {
            //header
            writer.println("\"source\",\"target\",\"type\",\"id\",\"label\",\"interval\",\"weight\"");
            //all relations
            for(Relation relation : Globals.web.getRelations()){
                writer.println(relation.getParent().getId() + "," + relation.getChild().getId() + ",\"" + relation.getName() + "\"," + relation.getId() + ",\"" + relation.getName() + "\",,");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
