import locale
from optparse import make_option

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

from docbow_project.docbow.models import MailingList


def get_object(model, ref):
    '''Try to get a model by id or by name'''
    if ref.isdigit():
        return model.objects.get(id=int(ref))
    else:
        return model.objects.get(name=ref)

class Command(BaseCommand):
    args = ''
    help = '''Create or update a list'''

    option_list = BaseCommand.option_list + (
            make_option("--add-list", action="append",
                help='add a list as a sublist', default=[]),
            make_option("--remove-list", action="append",
                help='remove list as a sublist', default=[]),
            make_option("--add-user", action="append",
                help='add a user member', default=[]),
            make_option("--remove-user", action="append",
                help='remove a user member', default=[]),
    )


    @transaction.commit_on_success
    def handle(self, *args, **options):
        locale.setlocale(locale.LC_ALL, '')
        locale_encoding = locale.nl_langinfo(locale.CODESET)
        mailing_list, created = MailingList.objects.get_or_create(
                name=args[0].decode(locale_encoding))
        try:
            for l in options['add_list']:
                l = get_object(MailingList, l)
                mailing_list.mailing_list_members.add(l)
            for l in options['remove_list']:
                l = get_object(MailingList, l)
                mailing_list.mailing_list_members.remove(l)
        except MailingList.DoesNotExist:
             raise CommandError('list %r does not exist' % l)
        try:
            for g in options['add_user']:
                g = get_object(User, g)
                mailing_list.members.add(g)
            for g in options['remove_user']:
                g = get_object(User, g)
                mailing_list.members.remove(g)
        except User.DoesNotExist:
            raise CommandError('user %r does not exist' % g)
