"""This module holds the tests for the exporters of the ``saba`` discrete_app"""

from datetime import timedelta

from constance.test import override_config

from django.core import mail
from django.utils import timezone

from mtp.apps.accounts.factories import MTPUserFactory

from .test_cases import BaseAssessmentsResultsToSabaTaskTestCase
from ..exporters import SabaResultsExporter
from ..factories import CertificationProgramUserStatusDjangoTaskFactory


class SabaResultsExporterTestCase(BaseAssessmentsResultsToSabaTaskTestCase):
    """Test the ``SabaResultsExporter`` exporter"""

    def test_extract_data_from_certifs(self):
        """Test the ``_extract_data`` method"""

        # a test failed task
        cpu_task_admin = CertificationProgramUserStatusDjangoTaskFactory(
            user=self.admin,
            certification=self.certification_complete_with_data,
            finished_at=timezone.now() - timedelta(minutes=5),
        )
        # attach a dummy result to the task
        dummy_result_admin = {
            'status': 'KO',
            'exception': 'An exception has occured',
            'exception_user_message': 'Message for the user',
            'executed_steps': [
                'parse_certification: OK',
                'get_trainee_details: KO'
            ],
            'steps': {
                'get_trainee_details': {
                    'success': False
                }
            },
        }
        cpu_task_admin.redis_instance.results = dummy_result_admin

        # a test successful task
        cpu_task_trainer = CertificationProgramUserStatusDjangoTaskFactory(
            user=self.trainer,
            certification=self.certification_complete_with_data,
            finished_at=timezone.now() - timedelta(minutes=5),
        )
        # attach a dummy result to the task
        dummy_result_trainer = {
            'status': 'OK',
        }
        cpu_task_trainer.redis_instance.results = dummy_result_trainer

        exporter = SabaResultsExporter()
        exporter._extract_data()

        training_admin = cpu_task_admin.certification.session.training
        training_trainer = cpu_task_trainer.certification.session.training

        expected_data = {
            self.admin: [
                [
                    cpu_task_admin.certification.user.external_id,
                    cpu_task_admin.certification.user.first_name,
                    cpu_task_admin.certification.user.last_name,
                    cpu_task_admin.certification.session.training.external_id,
                    str(cpu_task_admin.certification.session.start_date.date()),
                    training_admin.business_unit.name,
                    training_admin.job_profile.name,
                    dummy_result_admin['status'],
                    dummy_result_admin['exception_user_message'],
                    'parse_certification: OK\n'
                    'get_trainee_details: KO',
                    dummy_result_admin['exception'],
                    cpu_task_admin.pk,
                    cpu_task_admin.certification.pk,
                ]
            ],
            self.trainer: [
                [
                    cpu_task_trainer.certification.user.external_id,
                    cpu_task_trainer.certification.user.first_name,
                    cpu_task_trainer.certification.user.last_name,
                    cpu_task_trainer.certification.session.training.external_id,
                    str(cpu_task_trainer.certification.session.start_date.date()),
                    training_trainer.business_unit.name,
                    training_trainer.job_profile.name,
                    dummy_result_trainer['status'],
                    '',
                    '',
                    '',
                    cpu_task_trainer.pk,
                    cpu_task_trainer.certification.pk,
                ]
            ],
        }

        self.assertEqual(exporter.tasks_data, expected_data)

    @override_config(SABA_RECAP_EMAIL_RECIPIENTS='saba-test-account')
    def test_send_recap_email(self):
        """Test the ``send_recap_email`` method"""

        # let's create a user to match our setting SABA_RECAP_EMAIL_RECIPIENTS
        MTPUserFactory(username='saba-test-account')

        dummy_csv_row = ['data1', 'data2']

        csv_data = {
            self.trainee: [dummy_csv_row],
            self.trainer: [dummy_csv_row]
        }

        exporter = SabaResultsExporter()
        exporter.tasks_data = csv_data
        exporter.send_recap_email()

        # We should get 4 new mails to send:
        # 1 for trainee, 1 for trainer and 2 for 'saba-test-account'
        # since 'saba-test-account' receives both emails
        self.assertEqual(len(mail.outbox), 4)

        for sent_mail in mail.outbox:
            with self.subTest(sent_mail=sent_mail):
                # attachment is set
                self.assertEqual(len(sent_mail.attachments), 1)

                # CSV content looks good
                attachment_content = sent_mail.attachments[0][1]
                dummy_csv_str = ','.join(['"%s"' % item for item in dummy_csv_row])
                self.assertIn(dummy_csv_str, attachment_content)
