# -*- coding: utf-8 -*-
import datetime
from django.core.management.base import BaseCommand, CommandError

from coin.billing.create_subscriptions_invoices import create_all_members_invoices_for_a_period


class Command(BaseCommand):
    args = '[date=2011-07-04]'
    help = 'Create invoices for members subscriptions for date specified (or today if no date passed)'

    def handle(self, *args, **options):
        try:
            date = datetime.datetime.strptime(args[0], '%Y-%m-%d').date()
        except IndexError:
            date = datetime.date.today()
        except ValueError:
            raise CommandError(
                'Please enter a valid date : YYYY-mm-dd (ex: 2011-07-04)')

        self.stdout.write(
            'Create invoices for all members for the date : %s' % date)

        invoices = create_all_members_invoices_for_a_period(date)

        self.stdout.write(
            u'%d invoices were created' % len(invoices))

