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


class Command(BaseCommand):
    help = 'Update user enabled services according to WooCommerce \
    subscription.'

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

    def handle(self, *args, **options):
        ev = EmailValidator()
        email = options['email']
        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

        forced_update(user)
        msg = 'Services update forced on user {}.'.format(email)
        self.stdout.write(msg)
