import sys
import locale
from optparse import make_option

from django.core.management.base import BaseCommand
from django.db import transaction

from ...models import MailingList
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 mailing lists'''

    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, '')
        locale_encoding = locale.nl_langinfo(locale.CODESET)
        mailing_lists = MailingList.objects.prefetch_related('members', 
                'mailing_list_members')
        for arg in args:
            key, value = arg.split('=')
            mailing_lists = mailing_lists.filter(
                    **{key: value})
        tables = [('Id', 'Name', 'Members', 'List Members')]
        for mailing_list in mailing_lists:
            tables.append(map(unicode, (
                mailing_list.id,
                mailing_list.name,
                ','.join(m.name for m in mailing_list.mailing_list_members.all()),
                ','.join(g.username for g in mailing_list.members.all()))))
        if options['csv']:
            writer = UnicodeWriter(sys.stdout, encoding=locale_encoding)
            for row in tables:
                writer.writerow(row)
        else:
            print_table(tables)
