import locale
import os.path
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 django.core.files import File


from docbow_project.docbow.models import (MailingList, FileType, Document,
        AttachedFile)


def get_object(model, ref, name='name'):
    '''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 = '''Send a document'''

    option_list = BaseCommand.option_list + (
            make_option("--sender"),
            make_option("--to-list", action="append"),
            make_option("--to-user", action="append"),
            make_option("--filetype"),
            make_option("--description"),
    )

    @transaction.commit_on_success
    def handle(self, *args, **options):
        locale.setlocale(locale.LC_ALL, '')
        locale_encoding = locale.nl_langinfo(locale.CODESET)
        if 'sender' not in options:
            raise CommandError('missing --sender parameter')
        try:
            sender = get_object(User,
                    options['sender'].decode(locale_encoding), 'username')
        except User.DoesNotExist:
            raise CommandError('user %r does not exist' % options['sender'])
        to_lists = []
        try:
            for l in options.get('to)list') or []:
                l = get_object(MailingList, l.decode(locale_encoding))
                to_lists.append(l)
        except MailingList.DoesNotExist:
            raise CommandError('list %r does not exist' % l)
        to_users = []
        try:
            for l in options.get('to_user') or []:
                l = get_object(User, l.decode(locale_encoding), 'username')
                to_users.append(l)
        except User.DoesNotExist:
            raise CommandError('user %r does not exist' % l)
        if 'filetype' not in options:
            raise CommandError('missing --filetype parameter')
        try:
            filetype = get_object(FileType,
                    options['filetype'].decode(locale_encoding))
        except FileType.DoesNotExist:
            raise CommandError('filetype %r does not exist' % options['filetype'])
        if not to_users and not to_lists:
            print to_users, to_lists, options
            raise CommandError('you must specify at least one list or user '
                    'recipient using --to-list and --to-user.')
        document = Document(sender=sender, filetype=filetype)
        document.save()
        document.to_user = to_users
        document.to_list = to_lists
        if not args:
            raise CommandError('you must specify at least one file to attach '
                'to the sending.')
        for arg in args:
            if not os.path.isfile(arg):
                raise CommandError('file %r does not exist')
            AttachedFile.objects.create(name=arg.decode(locale_encoding),
                    content=File(file(arg)), document=document)
        document.post()
