from celery.utils.log import get_task_logger
from django.utils import timezone

from cart.models import ChosenReward
from ldapregister.models import LdapPerson
from limitmonitor.common import active_subscription

logger = get_task_logger(__name__)


def purge_users_pending_cart():
    pending_carts = ChosenReward.objects.filter(is_pending=True)
    now = timezone.now()
    total_pending = len(pending_carts)
    count_pending = 0

    for pending_cart in pending_carts:
        try:

            # Get User and username
            user = pending_cart.user
            username = user.username
            date_joined = user.date_joined
            time_pending = now - date_joined
            sub = active_subscription(user)
            paid = sub is not None

            if time_pending.total_seconds() > 60 * 60 * 24 and not paid:
                count_pending += 1

                # Delete LDAP entry
                try:
                    ldap_user = LdapPerson.objects.filter(uid=username)
                    ldap_user.delete()
                except Exception as e:
                    logger.exception("Could not delete user {} from LDAP.".format(username), e)

                # Delete WooCommerce account
                try:
                    user.delete_woocommerce_account()
                except Exception as e:
                    logger.exception("Could not delete user {} from WooCommerce.".format(username), e)

                # Finally delete user
                try:
                    user.delete()
                except Exception as e:
                    logger.exception("Could not delete user {} from Django.".format(username), e)

        except Exception as e:
            logger.exception("Could not delete pending user {}.".format(username), e)

    logger.info("Purged {count} of {total} pending users.".format(count=count_pending, total=total_pending))
