from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from django.core.management import BaseCommand
from django.urls import reverse

from corehq.apps.accounting.models import DefaultProductPlan, Subscription
from corehq.apps.domain.models import Domain
from corehq.apps.users.dbaccessors.all_commcare_users import get_mobile_user_count
from six.moves import map


class Command(BaseCommand):
    help = 'Print out a CSV containing a table of project space plan and number of mobile workers'

    def add_arguments(self, parser):
        parser.add_argument(
            'domain_names',
            metavar='domain',
            nargs='+',
        )

    def handle(self, domain_names, **kwargs):
        headers = ['Project Space Name', 'Project Space URL', 'Project Space Plan', '# of mobile workers']
        print(','.join(headers))
        for domain in [domain for domain in map(Domain.get_by_name, domain_names) if domain]:
            subscription = Subscription.get_active_subscription_by_domain(domain)
            plan_version = subscription.plan_version if subscription else DefaultProductPlan.get_default_plan_version()

            print(','.join([
                domain.name,
                reverse('domain_login', kwargs={'domain': domain}),     # TODO: make full URL
                plan_version.plan.name,
                str(get_mobile_user_count(domain.name, include_inactive=False)),
            ]))

@@ -375,33 +375,97 @@
 ort get_
-mobile_user_count
+all_user_rows, get_mobile_user_count%0Afrom corehq.apps.users.models import WebUser
 %0Afrom si
@@ -817,16 +817,51 @@
 wargs):%0A
+        # Report 1: Project Spaces%0A
         
@@ -1411,16 +1411,21 @@
 : domain
+.name
 %7D),     
@@ -1583,8 +1583,852 @@
     %5D))%0A
+%0A        # Report 2: Web Users%0A        headers = %5B'Name', 'Email Address', 'Role', 'Last login', 'Project Space Name', 'Project Space URL'%5D%0A        print(','.join(headers))%0A        for domain in %5Bdomain for domain in map(Domain.get_by_name, domain_names) if domain%5D:%0A            for user in get_all_user_rows(domain.name, include_web_users=True, include_mobile_users=False, include_inactive=False, include_docs=True):%0A                user = WebUser.wrap(user%5B'doc'%5D)%0A                print(','.join(%5B%0A                    user.full_name,%0A                    user.username,%0A                    user.role_label(domain.name),%0A                    user.last_login.strftime('%25Y/%25m/%25d %25H:%25M:%25S'),%0A                    domain.name,%0A                    reverse('domain_login', kwargs=%7B'domain': domain.name%7D),     # TODO: make full URL%0A                %5D))%0A

Add second set of data (web users)