from django.core.management.base import BaseCommand
from django.core.validators import EmailValidator, ValidationError
from django.conf import settings
from django.utils import timezone
from purist.models import User
from limitmonitor.common import forced_update, active_subscription
from limitmonitor.subscription import SubscriptionError


class Command(BaseCommand):
    help = "This command extends user's active subscription by the given number \
    of days."

    def add_arguments(self, parser):
        parser.add_argument('email',
                            type=str,
                            help='This is the email of the user that will get \
                            the subscription extended.')

        parser.add_argument('--days',
                            type=int,
                            help='Number of days to extend the subscription. \
                            Default is 5.',
                            default=5)

    def handle(self, *args, **options):
        ev = EmailValidator()
        email = options['email']
        extra_days = options['days']
        try:
            ev(email)
        except ValidationError as e:
            self.stdout.write(repr(e))
            return

        (username, domain) = email.split('@')

        if domain != settings.SITE_DOMAIN:
            msg = '{} does not belong to {} domain'
            self.stdout.write(msg.format(email, settings.SITE_DOMAIN))
            return
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            msg = 'User {} does not exist.'.format(email)
            self.stdout.write(msg)
            return

        sub = active_subscription(user)

        if sub is None:
            msg = 'User {} has *no* active subscriptions.'.format(email)
            self.stdout.write(msg)
            return

        old_ren_date = sub.next_payment_date
        sub.next_payment_date += timezone.timedelta(days=extra_days)

        try:
            sub.save()
        except SubscriptionError as e:
            self.stdout.write(
                'Error: Could not update WC subscription.\n'+repr(e)
            )
            return

        forced_update(user)
        msg = (
            '\nSubscription for user {} has been extended {} days, from {} to '
            '{}.'.format(
                email,
                extra_days,
                old_ren_date.strftime('%Y-%m-%d'),
                sub.next_payment_date.strftime('%Y-%m-%d')
            )
        )
        self.stdout.write(msg)
