import os
import unittest

from pytlex_core import Inconsistency_detector
from pytlex_core.Graph import Graph
from pytlex_core.Link import Link
from pytlex_core.TimeX import TimeX
from pytlex_core.Inconsistency_detector import detect_self_loop_for_graph
from pytlex_tests.jTLEX_Data import jTLEX_Counts

failed_parse = {'ABC19980304.1830.1636.tml', 'APW19980213.1320.tml', 'APW19980227.0468.tml', 'APW19980227.0489.tml'}

class InconsistencyDetectorTestCase(unittest.TestCase):

    def test_graph_with_looping_links_is_detected(self):
        graph_with_looping_links = get_graph_with_looping_links()
        links_with_self_loops = detect_self_loop_for_graph(graph_with_looping_links)

        assert(len(links_with_self_loops) == 1)

    def test_consistencies_against_jtlex(self):
        print()
        filepath = r"../pytlex_data/TimeBankCorpus"
        for subdir, dirs, files in os.walk(filepath):
            for filename in files:
                if filename not in failed_parse:
                    print(filename)
                    graph = Graph(filepath=filepath+"/"+filename)
                    self.assertEqual(not graph.consistency, filename in jTLEX_Counts.jTLEX_inconsistent_files)

def get_graph_with_looping_links() -> Graph:
    """
    returns a valid graph with links that self loop
    """
    graph = Graph()
    single_node = get_valid_node()

    # add single node
    graph.add_node(get_valid_node())

    # add self-looping link to graph
    link = get_looping_link(single_node)
    graph.add_link(link)

    # draw a link between the two nodes, rendering is a self-loop
    return graph

def get_looping_link(looping_node: TimeX) -> Link:
    """
    returns a valid link that has the same start_node and
    related_to_node value, effectively setting it to have a
    self-loop inconsistency.
    """

    link_data = {
            "link_id": get_link_id(),
            "link_tag": get_link_tag(),
            "rel_type": get_link_rel_type(),
            "start_node": looping_node,
            "related_to_node": looping_node,
            "signal": None,
            "origin_type": None,
            "syntax": None,
            }
    return Link(**link_data)

def get_link_id() -> int:
    return 0

def get_link_tag() -> str:
    return "TLINK"

def get_link_rel_type() -> str:
    return "BEFORE"

def get_valid_node() -> TimeX:
    return TimeX(50, "FUTURE_REF", True, "next wednesday")

if __name__ == '__main__':
    unittest.main()
