import sys
import locale
from optparse import make_option

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.db import transaction

from ...models import DocbowProfile
from ...unicodecsv import UnicodeWriter

def print_table(table):
    col_width = [max(len(x) for x in col) for col in zip(*table)]
    for line in table:
        line = u"| " + u" | ".join(u"{0:>{1}}".format(x, col_width[i])
                                for i, x in enumerate(line)) + u" |"
        print line

class Command(BaseCommand):
    args = ''
    help = '''List users'''

    option_list = BaseCommand.option_list + (
            make_option("--csv", action='store_true'),
    )

    @transaction.commit_on_success
    def handle(self, *args, **options):
        locale.setlocale(locale.LC_ALL, '')
        users = User.objects.prefetch_related('docbowprofile', 'groups',
                'mailing_lists')
        for arg in args:
            key, value = arg.split('=')
            users = users.filter(**{key: value})
        tables = [('Id', 'Username', 'First name', 'Last name', 'Email',
            'Mobile phone', 'Personal mail', 'Lists', 'Groups', 'Active', 'Superuser')]
        for user in users:
            try:
                mobile_phone = user.docbowprofile.mobile_phone
                personal_email = user.docbowprofile.personal_email
            except DocbowProfile.DoesNotExist:
                mobile_phone = ''
                personal_email = ''
            tables.append(map(unicode, (
                user.id,
                user.username,
                user.first_name,
                user.last_name,
                user.email,
                mobile_phone,
                personal_email,
                ','.join(m.name for m in user.mailing_lists.all()),
                ','.join(g.name for g in user.groups.all()),
                user.is_active,
                user.is_superuser)))
        if options['csv']:
            writer = UnicodeWriter(sys.stdout, encoding=locale.nl_langinfo(locale.CODESET))
            for row in tables:
                writer.writerow(row)
        else:
            print_table(tables)



