# -*- coding: utf-8 -*-

import os
import os.path as osp
import sys
import re
import platform
import socket
import getpass
from distutils import sysconfig
from subprocess import Popen, PIPE

_unique_tmpdir = True


def _get_version():
    """get default Code_Aster version used for testcases"""
    fconfig = osp.join(confdir, 'aster')
    with open(fconfig, 'r') as f:
        txt = f.read()
    mat = re.search('^default_vers *: *(.+)', txt, re.M)
    assert mat != None, 'default_vers not found in %s' % fconfig
    vers = mat.group(1)
    return vers

def set_version(vers):
    global aster_version, dict_conf
    aster_version = dict_conf['ASTER_VERSION'] = vers

def _get_tmpdir():
    """use current temporary directory"""
    fconfig = osp.join(confdir, 'asrun')
    with open(fconfig, 'r') as f:
        txt = f.read()
    mat = re.search('rep_trav *: *(.+)', txt)
    assert mat != None, 'rep_trav not found in %s' % fconfig
    num = os.getpid()
    if _unique_tmpdir:
        num = "resu"
    tmpdir = osp.expandvars(osp.join(mat.group(1), "unittest.as_run.%s" % num))
    return tmpdir

def execcmd(cmd, trace_name, return_output=False):
    """execute a command and write output and error to trace_name.xxx"""
    ferr = open(osp.join(tmpdir, trace_name + ".err"), "w")
    ferr.write("Command: %s\n" % (' '.join(cmd)))
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    out, err = p.communicate()
    with open(osp.join(tmpdir, trace_name + ".out"), "w") as f:
        f.write(out)
    ferr.write(err)
    ferr.close()
    result = p.returncode
    if return_output:
        result = (p.returncode, out)
    return result

def init(hostlist):
    try:
        os.makedirs(tmpdir)
    except OSError:
        pass
    _check_hosts(hostlist)

def on_dev_machine():
    return platform.uname()[1] == "cli70cx" and \
        osp.abspath(osp.join(__file__, os.pardir, os.pardir)).endswith('ASTK_SERV')

def _check_hosts(hostlist):
    # fill the available remote hosts
    from data import available_hosts
    from asrun.run import AsRunFactory
    if not hostlist:
        return
    hosts = dict([hdir.split(':') for hdir in hostlist.split(',')])
    run = AsRunFactory()
    for host, root in list(hosts.items()):
        if run.Ping(host):
            available_hosts[host] = root
    if len(available_hosts) > 0:
        dict_conf['remhost'] = list(available_hosts.keys())[0]


# to find asrun package
if os.environ.get('ASTER_ROOT'):
    sys.path.append(sysconfig.get_python_lib(prefix=os.environ['ASTER_ROOT']))

try:
    from asrun.installation import aster_root
except ImportError:
    _test = osp.abspath(osp.join(__file__, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir))
    sys.path.append(sysconfig.get_python_lib(prefix=_test))
    try:
        from asrun.installation import aster_root
    except ImportError:
        print("Import of asrun package failed !")
        sys.exit(1)

from asrun.installation import confdir
if not osp.exists(osp.join(confdir, "asrun")):
    print("file not found:", osp.join(confdir, "asrun"))
    print("A valid installation should contain:\n %s, %s..." \
        % (osp.join(aster_root, "bin"), confdir))
    sys.exit(1)

print("Import of asrun package succeed (from %s)" % aster_root)
from asrun.run import AsRunFactory

as_run_cmd = AsRunFactory().get_as_run_cmd()
del AsRunFactory


aster_version = _get_version()
tmpdir = _get_tmpdir()

dict_conf = {
    'ASTER_ROOT' : aster_root,
    'ASTER_VERSION' : aster_version,
    'PYTHONEXECUTABLE' : sys.executable,
    'CONFIG_FILE_LINE' : os.environ.get('CONFIG', ""),
    'DATA' : osp.abspath(osp.join(__file__, os.pardir, "datafiles")),
    'TMPDIR' : tmpdir,
    'as_run' : as_run_cmd,
    'localhost' : socket.gethostname(),
    'localuser' : getpass.getuser(),
    'remhost' : '',
}
