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

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

from common import dict_conf, execcmd, tmpdir
from data   import study_dvp_export, study_dvp_full_export

import asrun
from asrun.run          import AsRunFactory
from asrun.profil       import AsterProfil
from asrun.calcul       import AsterCalcul, parse_submission_result
from asrun.job          import parse_actu_result


class TestUseDvpt(unittest.TestCase):

    def test01_using_api(self):
        export = osp.join(tmpdir, "study_dvp.export")
        with open(export, "w") as f:
            f.write(study_dvp_export % dict_conf)
        run = AsRunFactory()
        prof = AsterProfil(run=run, filename=export)

        calc = AsterCalcul(run, prof=prof, pid=run.get_pid())
        jret, out = calc.start()
        calc.wait()
        assert run.GetGrav(calc.diag) == 1
        assert osp.isfile(calc.flash('output'))
        with open(calc.flash('output'), "r") as f:
            output = f.read()
        assert len(re.findall("MCTEST_CAPY", output, re.M)) == 2, calc.flash('output')
        calc.kill()


    def test02_full_cmdline(self):
        #
        run = AsRunFactory()
        export = osp.join(tmpdir, "study_dvp_full.export")
        with open(export, "w") as f:
            f.write(study_dvp_full_export % dict_conf)
        exe = osp.join(tmpdir, 'aster.exe')
        # to check that it doesn't try to copy exec as a data
        if osp.exists(exe):
            os.remove(exe)
        cmd = dict_conf["as_run"] + ["--serv", export]
        iret, out = execcmd(cmd, "study_dvp_full.1", return_output=True)
        nomjob = "study_dvp_full"
        assert iret == 0
        jobid, queue, studyid = parse_submission_result(out)
        assert jobid.strip() != ""
        assert studyid.strip() != ""

        ended = False
        nmax = 30
        i = 0
        while not ended and i < nmax:
            i += 1
            time.sleep(1.)
            cmd = dict_conf["as_run"] + ["--actu", jobid, nomjob, "interactif"]
            iret, out = execcmd(cmd, "study_dvp_full.2", return_output=True)
            assert iret == 0
            etat, diag, node, tcpu, wrk, queue = parse_actu_result(out)
            ended = etat == "ENDED"
        assert ended, 'not ended after %d iterations' % nmax
        assert run.GetGrav(diag) == 1, diag
        cmd = dict_conf["as_run"] + ["--del", jobid, nomjob, "interactif"]
        iret = execcmd(cmd, "study_dvp_full.3")
        assert iret == 0


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