import os
import re
import subprocess
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape

heideltime_path = 'tools/heideltime'
heideltime_jar_name = 'de.unihd.dbs.heideltime.standalone.jar'
heideltime_root_regex = re.compile('<TimeML>(.*?)</TimeML>', re.MULTILINE | re.DOTALL)
date_format_regex = re.compile('^\d{4}-\d{2}-\d{2}')


def mentioned_dates_by_sentence(filename, pub_date):
    print(filename)

    # create a temporary copy of the file with interfering characters escaped
    escaped_filename = str(filename) + '.escaped'
    with open(filename, encoding='utf-8') as f, open(escaped_filename, 'w', encoding='utf-8') as g:
        for line in f:
            g.write(escape(line))

    # change to heideltime directory (and keep track of the path back to the root)
    working_dir = os.getcwd()
    heideltime_abs_path = os.path.abspath(heideltime_path)
    root_path = os.path.commonprefix([heideltime_abs_path, working_dir])
    path_from_heideltime_to_root = os.path.relpath(root_path, heideltime_abs_path)
    os.chdir(heideltime_path)

    dates_by_sentences = []

    heideltime_output = subprocess.run([
        'java',
        '-jar', heideltime_jar_name,
        os.path.join(path_from_heideltime_to_root, str(escaped_filename)),
        '-t', 'NEWS',
        '-dct', pub_date
    ], capture_output=True).stdout.decode(encoding='utf-8')

    sentences = heideltime_root_regex.search(heideltime_output)[1].strip().split('\n')
    for sentence in sentences:
        if not sentence.strip():
            continue
        dates_for_this_sentence = []
        root = ET.fromstring('<root>' + sentence + '</root>')
        for child in root:
            if child.tag == 'TIMEX3' and child.attrib['type'] in ['DATE', 'TIME']:
                match = date_format_regex.match(child.attrib['value'])
                if match is not None:
                    dates_for_this_sentence.append(match[0])
        dates_by_sentences.append(dates_for_this_sentence)

    # change directory back
    os.chdir(working_dir)

    # remove the temporary copy
    while True:
        try:
            os.remove(escaped_filename)
            break
        except PermissionError:
            # you can do it, I believe in you
            continue

    return dates_by_sentences
