"""Clear random data.

This script is used to periodically clear the database in the kaavish demo app.
It removes some of data generated by `populatedb` such as example orders or
products. It doesn't however remove any shop's configuration such as an admin
account, site settings or menus.
"""

from __future__ import unicode_literals

from django.core.management.base import BaseCommand

from kaavish.account.models import User
from kaavish.checkout.models import Checkout
from kaavish.discount.models import Sale, Voucher
from kaavish.order.models import Order
from kaavish.payment.models import Payment, Transaction
from kaavish.product.models import Product
from kaavish.shipping.models import ShippingMethod


class Command(BaseCommand):
    help = "Clear database preserving staff accounts and configuration"

    def handle(self, *args, **kwargs):
        Checkout.objects.all().delete()
        self.stdout.write("Removed checkouts")

        Transaction.objects.all().delete()
        self.stdout.write("Removed transactions")

        Payment.objects.all().delete()
        self.stdout.write("Removed payments")

        Order.objects.all().delete()
        self.stdout.write("Removed orders")

        Product.objects.all().delete()
        self.stdout.write("Removed products")

        Sale.objects.all().delete()
        self.stdout.write("Removed sales")

        ShippingMethod.objects.all().delete()
        self.stdout.write("Removed shipping methods")

        Voucher.objects.all().delete()
        self.stdout.write("Removed vouchers")

        # Delete all users except for staff members.
        staff = User.objects.filter(is_staff=True)
        User.objects.exclude(pk__in=staff).delete()
        self.stdout.write("Removed customers")

        # Remove addresses of staff members.
        for user in staff:
            user.addresses.all().delete()
        self.stdout.write("Removed staff addresses")