""" Send reminders for contribution that are about to expire

It offers a way for contributors to opt-in keeping the data one year more (or
deleting it right now).

Reminders are sent when the script is called exactly `n` days before the
expiration date.

This `n` can be configured via `DATA_EXPIRATION_REMINDERS` setting.
"""

from django.conf import settings
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import get_template


from ...models import Contrib
from ...tokens import ContribTokenManager


class Command(BaseCommand):
    help = __doc__

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run', default=False, action='store_true',
            help="Do not actually send emails, just pretend to")

    def handle(self, dry_run, *args, **options):
        if dry_run:
            self.stderr.write('DRY RUN MODE: we do not actually send emails.')

        for ndays in settings.DATA_EXPIRATION_REMINDERS:
            expirating_contribs = Contrib.objects.expires_in_days(ndays)
            for contrib in expirating_contribs:
                if not contrib.email:
                    self._warn_no_email(contrib, ndays)
                else:
                    if not dry_run:
                        self.send_expiration_reminder(contrib, ndays)
                    self._log_sent_email(contrib, ndays)

    def _warn_no_email(self, contrib, ndays):
        self.stderr.write(
            'WARNING : the contribution {} is about to expire in {} days but'
            + 'do not define a contact email.'.format(
                contrib, ndays))

    def _log_sent_email(self, contrib, ndays):
        self.stderr.write(
            "Sent reminder email to for {} expiration in {} days".format(
                contrib, ndays))

    def send_expiration_reminder(self, contrib, ndays):
        subject = get_template(
            'contribmap/mails/expiration_reminder.subject')
        body = get_template(
            'contribmap/mails/expiration_reminder.txt')

        mgmt_token = ContribTokenManager().mk_token(contrib)

        context = {
            'contrib': contrib,
            'ndays': ndays,
            'isp': settings.ISP,
            'management_link': contrib.make_management_url(mgmt_token),
        }
        send_mail(
            subject.render(context),
            body.render(context),
            settings.DEFAULT_FROM_EMAIL,
            [contrib.email],
        )