'''

'''
import datetime
import tempfile
import unittest

from path import Path
from tests import HERE

from core import constants, config
from core.process import process


class Test(unittest.TestCase):

    def loadconfig(self):
        constants.USER_DATA_PATH = HERE / r"rsc\test_process\userdata.yaml"
        config.load()

    def test_process(self):

        self.loadconfig()

        xmlpath = HERE / r"rsc\test_process\testfile.xml"

        with tempfile.TemporaryDirectory() as outputdir:

            outputdir = Path(outputdir)

            config.CONFIG["repertoire_sortie"] = outputdir

            # Returned results
            files, mails = process(xmlpath)

            self.assertEqual(files, [outputdir / r'testfile\Recepisse_DICT.pdf',
                                      outputdir / r'testfile\Recepisse_DT.pdf'])

            # mails
            mail1, mail2 = mails

            self.assertEqual(mail1.to, 'dict@spacex.net')
            self.assertEqual(mail1.subject, 'Réponse à la demande 000001')
            self.assertEqual(mail1.content, 'Veuillez trouver ci-joint la réponse à votre demande.\nCordialement,')
            self.assertEqual(mail1.attachments, [])

            self.assertEqual(mail2.to, 'dt@spacex.net')
            self.assertEqual(mail2.subject, 'Réponse à la demande 000001')
            self.assertEqual(mail2.content, 'Veuillez trouver ci-joint la réponse à votre demande.\nCordialement,')
            self.assertEqual(mail2.attachments, [])

            # Generated files
            outputdir /= 'testfile'

            self.assertTrue(Path(outputdir / 'contact.txt').exists())
            with open(outputdir / 'contact.txt') as f:
                self.assertEqual(f.read(), "dict@spacex.net\ndt@spacex.net")

            self.assertTrue(Path(outputdir / 'data.fdf').exists())

            with open(outputdir / 'data.fdf') as f, open(HERE / r'rsc\test_process\ref.fdf') as fref:
                today = datetime.date.today()
                self.assertEqual(f.read(), fref.read().format(day=today.day,
                                                              month=today.month,
                                                              year=today.year))

            self.assertTrue(Path(outputdir / 'testfile.xml').exists())
            with open(xmlpath) as f1, open(outputdir / 'testfile.xml') as f2:
                self.assertEqual(f1.read(), f2.read())

            self.assertTrue(Path(outputdir / 'Recepisse_DICT.pdf').exists())
            self.assertTrue(Path(outputdir / 'Recepisse_DT.pdf').exists())


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