import subprocess
import xmltodict
import os
import sys
import logging
import stat
from functools import lru_cache

import iepy
from iepy.utils import DIRS, unzip_from_url


logger = logging.getLogger(__name__)


def detect_java_version():
    java_cmd = os.getenv('JAVAHOME')
    if not java_cmd:
        print('Environment variable JAVAHOME not defined.')
        sys.exit(-1)

    here = os.path.dirname(os.path.realpath(__file__))
    jar = os.path.join(here, 'utils', 'get-java-version.jar')
    jversion = subprocess.check_output([java_cmd, "-jar", jar], stderr=subprocess.PIPE)
    return int(jversion.strip())


JAVA_VERSION = detect_java_version()


_STANFORD_BASE_URL = "http://nlp.stanford.edu/software/"
if JAVA_VERSION < 8:
    # Stanford Core NLP 3.4.1 - Last version to support Java 6 and Java 7
    # Pitifully Stanford folks have a public name ("version") of their releases that isn't
    # used on their download urls. So, 3.4.1 is "stanford-corenlp-full-2014-08-27"
    _CORENLP_VERSION = "stanford-corenlp-full-2014-08-27"
    DOWNLOAD_URL = _STANFORD_BASE_URL + _CORENLP_VERSION + ".zip"
    DOWNLOAD_URL_ES = _STANFORD_BASE_URL + 'stanford-spanish-corenlp-2014-08-26-models.jar'
    DOWNLOAD_URL_DE = _STANFORD_BASE_URL + 'stanford-german-2016-01-19-models.jar'
    _FOLDER_PATH = os.path.join(DIRS.user_data_dir, _CORENLP_VERSION)
    COMMAND_PATH = os.path.join(_FOLDER_PATH, "corenlp.sh")
else:
    # Stanford Core NLP 3.5.2
    _CORENLP_VERSION = "stanford-corenlp-full-2015-04-20"
    DOWNLOAD_URL_ES = _STANFORD_BASE_URL + 'stanford-spanish-corenlp-2015-01-08-models.jar'
    DOWNLOAD_URL_DE = _STANFORD_BASE_URL + 'stanford-german-2016-01-19-models.jar'