from django.core.management.base import BaseCommand
from purist.models import User
import time


class Command(BaseCommand):
    help = "Populate billing_email value for users that don't have it set. If \
            the user has a WooCommerce email this value will be used. \
            Otherwise the User.get_identity() identity will be used."

    def add_arguments(self, parser):
        parser.add_argument('--wait',
                            type=int,
                            help='Number of seconds to wait between users. \
                            Default is 0.',
                            default=0)

    def handle(self, *args, **options):
        wait_time = options['wait']
        # Get all users with billing_email = ''
        usr_empty = User.objects.filter(billing_email='')

        self.stdout.write('Processing users with no billing_email')
        for user in usr_empty:
            wc_email = user.get_woocommerce_billing_email()
            if wc_email is None or wc_email == '':
                user.billing_email = user.get_identity()
            else:
                user.billing_email = wc_email
            user.save()
            self.stdout.write(' User {}:'.format(user.username))
            self.stdout.write('   New billing_email: {}'.format(
                user.billing_email))
            time.sleep(wait_time)
