package edu.fiu.jtlex.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;

import org.junit.jupiter.api.Test;

public class SystemTest {

	public class Client {
		FileInputStream file;
		TimeMLParser parser;

		public Client(String path) throws FileNotFoundException {
			this.file = new FileInputStream(path);
			this.parser = new TimeMLParser();
		}

		public IGraph generateGraph() {
			Text txtObject = (Text) parser.parse(this.file);
			IGraph graph = new Graph();

			Set<ITimex> nodes1 = txtObject.getTimexes();
			Set<IInstance> nodes2 = txtObject.getInstances();

			Set<ILink> links = txtObject.getLinks();

			for (ITimex node : nodes1) {
				graph.addNode(node);
			}
			for (IInstance node : nodes2) {
				graph.addNode(node);
			}
			for (ILink link : links) {
				graph.addLink(link);
			}
			return graph;
		}
	}

	@Test
	void inconsistenciesTimeBankCorpus() {

		String wd = "/Users/luisrobaina/eclipse-workspace/edu.fiu.jtlex/data/The TimeBank Corpus";
		File file = new File(wd);
		String[] paths = file.list();

		try {
			FileWriter myWriter = new FileWriter("CorpusReport.txt");
			long start = System.currentTimeMillis();
	        
			for (String path : paths) {
				if (!path.contains(".tml") || path.equals("WSJ900813-0157.tml")) {
					continue;
				}
				System.out.println(path);
				System.out.println("=============");
				
				myWriter.write("TimeML File: " + path + "\n at: " + wd + "/" + path + "\n");

				Client client = new Client(wd + "/" + path);
				IGraph graph = client.generateGraph();
				
				myWriter.write("--------Graph Info-------\n");

				myWriter.write(testUtils.graphAsString(graph));

				// partition the graph
				ArrayList<IGraph> partitions = IGraphPartitioner.partitionGraph(graph);

				myWriter.write("\nPARTITIONS:\n");
				int i = 0;
				for (IGraph partition : partitions) {
					myWriter.write("\nPARTITION " + (i++) + "\n");

					myWriter.write(testUtils.graphAsString(partition));

					Set<IGraph> subGraphs = InconsistencyDetector.generateInconsistentSubgraphs(partition);

					myWriter.write("\n\t\tINCONSISTENT SUBGRAPHS:\n");

					if (subGraphs == null) {
						myWriter.write("\t\tNONE\n");
						continue;
					}
					for (IGraph g : subGraphs) {
						// Inconsistency subgraphs.
						myWriter.write(testUtils.graphAsString(g));
						myWriter.write("\nType: " + g.getNodesCount() + " inconcistency\n");
					}
					myWriter.write("---------------------------");
				}
				myWriter.write("================================\n\n");
			}
	        System.out.println("It took: " + ((System.currentTimeMillis() - start)/1000.00) + " seconds.");
			myWriter.close();
			System.out.println("FINISHED REPORT ON " + paths.length + " TimeML FILES.");

		} catch (IOException e) {
			System.out.println("Error: " + e);
		}
	}
}
