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


class Command(BaseCommand):
    help = """Removes user from all LDAP groups, terminates tunnel account,
    deactivates WooCommerce account, marks the user as inactive, sets
    a gibberish LDAP password and sets purge value to default value
    0."""

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

        parser.add_argument('--purge_n',
                            type=int,
                            help='Purge number to be used for the user. \
                            Default is 0.',
                            default=0)

        parser.add_argument('--full',
                            action='store_true',
                            help='Deletes the user from middleware DB, LDAP \
                            and WooCommerce.')

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

        orders = user.get_woocommerce_orders()
        if orders is not None:
            for order in orders:
                try:
                    parsed_o = parse_order(order)
                except OrderParseError:
                    msg = 'Error parsing orders for user: {}'.format(email)
                    self.stdout.write(msg)
                    return
                if parsed_o['is_pending']:
                    msg = 'User {} has pending orders.'.format(email)
                    self.stdout.write(msg)
                    return

        msg = 'Deleting user {}...'.format(email)
        self.stdout.write(msg)
        delete_account(user, purge_n=purge_n, purge=full)

        if full:
            msg = 'User {} fully deleted.'.format(email)
        else:
            msg = 'User {} deleted and marked for purge {}.'.format(email,
                                                                    purge_n)
        self.stdout.write(msg)
