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

import os
import unittest
import random
from glob import glob

from common import dict_conf, tmpdir

import asrun
from asrun.installation import aster_root
from asrun.run          import AsRunFactory
from asrun.config       import AsterConfig
from asrun.execution    import build_test_export, build_export_from_files


class TestBuildExport(unittest.TestCase):

    def setUp(self):
        """Initialize run and conf object.
        """
        self.run = AsRunFactory()
        vers = dict_conf['ASTER_VERSION']
        assert vers is not None, "default_vers is None! Check aster configuration file"
        vers = self.run.get_version_path(vers)
        # print "aster_root=", aster_root, vers
        self.REPREF = os.path.join(aster_root, vers)
        self.run.PrintExitCode = False
        ficconf = os.path.join(self.REPREF, 'config.txt')
        self.conf = AsterConfig(ficconf, self.run)


    def test01_build_random_testcase_export(self):
        lf = glob(os.path.join(self.REPREF, "tests", "*.comm"))
        random.shuffle(lf)
        test = os.path.splitext(os.path.basename(lf[0]))[0]
        prof = build_test_export(self.run, self.conf, self.REPREF, [], test)
        prof.update_content()
        lcomm = prof.Get('D', 'comm')
        assert len(lcomm) >= 1
        df = lcomm[0]
        assert df['ul'] == 1
        assert df['isrep'] == False
        assert df['compr'] == False
        assert df['type'] == 'comm'
        assert os.path.isfile(df['path'])


    def test02_build_efica01a_export(self):
        prof = build_test_export(self.run, self.conf, self.REPREF, [], "efica01a")
        prof.update_content()
        assert len(prof.Get('D', 'comm')) == 3
        assert len(prof.Get('D', 'mail')) == 1
        assert len(prof.Get('D', 'msup')) == 1
        llibr = prof.Get('D', 'libr')
        assert len(llibr) == 3
        lul = [df['ul'] for df in llibr]
        lul.sort()
        assert lul == [11, 21, 22]


    def test03_build_export_from_files_list(self):
        lf = ["toto.comm", "toto.mail", "toto.34", "toto.mgib%"]
        prof = build_export_from_files(self.run, lf)
        prof.update_content()
        lcomm = prof.Get('D', 'comm')
        assert len(lcomm) == 1
        lmail = prof.Get('D', 'mail')
        assert len(lmail) == 1
        llibr = prof.Get('D', 'libr')
        assert len(llibr) == 1
        df = llibr[0]
        assert df['ul'] == 34
        assert df['isrep'] is False
        assert df['compr'] is False
        assert df['type'] == 'libr'
        msg = prof.check(error=False)
        assert len(msg) > 0, prof.get_content()


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