#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import os.path as osp
import re
import unittest
import time

from common import dict_conf, execcmd, tmpdir, aster_version
from data   import study_export, available_hosts

import asrun
from asrun.run import AsRunFactory
from asrun.profil import AsterProfil, ExportEntry
from asrun.calcul import parse_submission_result
from asrun.client import MULTIDIR
from asrun.job import parse_actu_result
from asrun.common.sysutils import short_hostname


def build_prof(nomjob, resoncli):
    prof = AsterProfil()
    prof.parse(study_export % dict_conf)
    prof['nomjob'] = nomjob
    prof['tpsjob'] = 1
    prof['multiple'] = 'yes'
    prof['multiple_result_on_client'] = resoncli
    lhosts = [dict_conf['localhost'],] + list(available_hosts.keys())
    #lhosts = available_hosts.keys()
    prof['multiple_server_list'] = " ".join(lhosts)
    prof.add(ExportEntry(osp.join(tmpdir, nomjob + '.repe'),
                         type='repe', isrep=True, result=True))
    return prof

def study(resoncli):
    assert len(available_hosts) > 0, "no remote host available."
    nomjob = 'multi_study_' + resoncli
    run = AsRunFactory()
    prof = build_prof(nomjob, resoncli)

    export = osp.join(tmpdir, "%s.export" % nomjob)
    prof.WriteExportTo(export)
    cmd = dict_conf["as_run"] + ["--serv", export]
    iret, out = execcmd(cmd, "%s.1" % nomjob, return_output=True)
    assert iret == 0
    jobid, queue, studyid = parse_submission_result(out)
    assert jobid.strip() != ""
    assert studyid.strip() != "" and studyid == jobid
    etat = 'RUN'
    while etat != 'ENDED':
        cmd = dict_conf["as_run"] + ["--actu", jobid, nomjob, "interactif"]
        iret, out = execcmd(cmd, "%s.2" % nomjob, return_output=True)
        etat, diag, node, tcpu, wrk, queue = parse_actu_result(out)
        if etat != "ENDED":
            time.sleep(0.5)
    assert run.GetGrav(diag) <= 1, "diag : %s, more details in ~/flasheur/%s.o%s" \
        % (diag, nomjob, jobid)
    # check that $HOME/MULTI/multi_study_`host` exists
    multidir = osp.expandvars(MULTIDIR)
    resdir = osp.join(multidir, '%s_%s' % (nomjob, dict_conf['localhost']))
    assert osp.isfile(osp.join(resdir, nomjob + '.repe', 'parameter'))
    for host in list(available_hosts.keys()):
        host = short_hostname(host)
        if resoncli == "yes":
            resdir = osp.join(multidir, '%s_%s' % (nomjob, host))
            flashdir = osp.join(multidir, '%s_%s' % (nomjob, host), 'flash')
        else:
            # this will fail if MULTIDIR change !
            resdir = '%s:%s' % (host, osp.join('MULTI', '%s_%s' % (nomjob, host)))
            flashdir = '%s:%s' % (host, osp.join('MULTI', '%s_%s' % (nomjob, host), 'flash'))
        assert run.IsDir(resdir), "results on found at %s" % resdir
        assert run.IsDir(flashdir), "flash directory on found at %s" % flashdir
    cmd = dict_conf["as_run"] + ["--del", jobid, nomjob, "interactif"]
    iret, out = execcmd(cmd, "%s.3" % nomjob, return_output=True)
    assert iret == 0

def astout():
    assert len(available_hosts) > 0, "no remote host available."
    run = AsRunFactory()
    prof = AsterProfil()
    nomjob = 'multi_astout'
    resoncli = "yes"
    prof['nomjob'] = nomjob
    prof['actions'] = 'astout'
    prof['version'] = aster_version
    prof['tpsjob'] = 1
    prof['memjob'] = 1024*16
    prof['multiple'] = 'yes'
    prof['multiple_result_on_client'] = resoncli
    lhosts = [dict_conf['localhost'],] + list(available_hosts.keys())
    #lhosts = available_hosts.keys()
    prof['multiple_server_list'] = " ".join(lhosts)
    flist = osp.join(tmpdir, nomjob + '.list')
    with open(flist, 'w') as f:
        f.write('ttnl02b\nssls122c')
    prof.add(ExportEntry(flist, type='list', data=True))
    prof.add(ExportEntry(osp.join(tmpdir, nomjob + '.resu_test'),
                         type='resu_test', isrep=True, result=True))
    prof.add(ExportEntry(osp.join(tmpdir, nomjob + '.flash'),
                         type='flash', isrep=True, result=True))

    export = osp.join(tmpdir, "multi_astout.export")
    prof.WriteExportTo(export)
    cmd = dict_conf["as_run"] + ["--serv", export]
    iret, out = execcmd(cmd, "multi_astout.1", return_output=True)
    assert iret == 0
    jobid, queue, studyid = parse_submission_result(out)
    assert jobid.strip() != ""
    assert studyid.strip() != "" and studyid == jobid
    etat = 'RUN'
    while etat != 'ENDED':
        cmd = dict_conf["as_run"] + ["--actu", jobid, nomjob, "interactif"]
        iret, out = execcmd(cmd, "multi_astout.2", return_output=True)
        etat, diag, node, tcpu, wrk, queue = parse_actu_result(out)
        if etat != "ENDED":
            time.sleep(0.5)
    assert run.GetGrav(diag) <= 1, "diag : %s, more details in ~/flasheur/%s.o%s" \
        % (diag, nomjob, jobid)
    # check results
    multidir = osp.expandvars(MULTIDIR)
    for host in lhosts:
        host = short_hostname(host)
        resdir = osp.join(multidir, '%s_%s' % (nomjob, host), nomjob + '.resu_test')
        assert osp.isdir(resdir), "results directory not found: %s" % resdir
        nook = osp.join(resdir, "NOOK")
        assert not osp.isfile(nook), "test(s) failed, see %s" % nook
        res = osp.join(resdir, "RESULTAT")
        assert osp.isfile(res), "result file not found: %s" % res
        # check flash
        flashdir = osp.join(multidir, '%s_%s' % (nomjob, host), nomjob + '.flash')
        assert osp.isdir(flashdir), "flash directory not found: %s" % flashdir
    cmd = dict_conf["as_run"] + ["--del", jobid, nomjob, "interactif"]
    iret, out = execcmd(cmd, "multi_astout.3", return_output=True)
    assert iret == 0


class TestMultiple(unittest.TestCase):

    def test01a_study(self):
        study("yes")

    def test01b_study(self):
        study("no")

    def test02_astout(self):
        astout()


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