from django.core.management.base import BaseCommand, CommandError
from django.conf import settings

from optparse import make_option
from bson.json_util import dumps
from pymongo import MongoClient


class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--filename', '-f',
                    dest='filename',
                    help='Sets the name of the dumped data file.'),
    )

    help = "Dumps data (in JSON) from the MongoDB database.\n\n" \
           "Usage: manage.py mongo_dump MODEL"

    def handle(self, *args, **options):
        if not args:
            raise CommandError('Please specify a model in Mongo database to '
                               'dump its existent data.')

        filename = options.get('filename')

        connection = MongoClient()
        db = connection[settings.MONGODB_NAME]

        collection = db[args[0]]

        if not filename:
            filename = args[0] + '.json'

        with open(filename, 'w') as f:
            for doc in collection.find():
                f.write(dumps(doc) + '\n')