import json
from datetime import datetime

from django.core.management import BaseCommand, CommandError

from dimagi.utils.web import json_handler

from corehq.apps.case_importer.do_import import do_import
from corehq.apps.case_importer.util import ImporterConfig, get_spreadsheet
from corehq.apps.users.models import WebUser


class Command(BaseCommand):
    help = "import cases from excel manually."

    def add_arguments(self, parser):
        parser.add_argument('export_file')
        parser.add_argument('config_file')
        parser.add_argument('domain')
        parser.add_argument('user_id')

    def handle(self, export_file, config_file, domain, user_id, **options):
        start = datetime.utcnow()

        if '@' in user_id:
            user = WebUser.get_by_username(user_id)
        else:
            user = WebUser.get(user_id)
        if not user.is_member_of(domain):
            raise CommandError("%s can't access %s" % (user, domain))

        with open(config_file, 'r', encoding='utf-8') as f:
            config = ImporterConfig.from_json(f.read())

        config.couch_user_id = user._id
        with get_spreadsheet(export_file) as spreadsheet:
            print(json.dumps(do_import(spreadsheet, config, domain),
                             default=json_handler))
            print('finished in %s seconds' % (datetime.utcnow() - start).seconds)

@@ -86,22 +86,8 @@
 mand
-, CommandError
 %0A%0Afr
@@ -264,82 +264,546 @@
 eet%0A
-from corehq.apps.users.models import WebUser%0A%0A%0Aclass Command(BaseCommand):
+%0A%0Aclass Command(BaseCommand):%0A    %22%22%22%0A    Import cases locally - useful for large imports or if you're trying to iterate on%0A    an import in a dev environment.%0A%0A    The easiest way to generate the config_file argument for this command is to add the following%0A    lines to case_importer.views.excel_commit and run the import once from the web UI:%0A%0A      config = importer_util.ImporterConfig.from_request(request)%0A      # add these two lines after the above one%0A      import json%0A      print(json.dumps(config.to_dict(), indent=2))%0A    %22%22%22
 %0A   
@@ -811,17 +811,17 @@
 help = %22
-i
+I
 mport ca
@@ -1011,47 +1011,8 @@
 in')
-%0A        parser.add_argument('user_id')
 %0A%0A  
@@ -1067,17 +1067,8 @@
 ain,
- user_id,
  **o
@@ -1115,254 +1115,8 @@
 ()%0A%0A
-        if '@' in user_id:%0A            user = WebUser.get_by_username(user_id)%0A        else:%0A            user = WebUser.get(user_id)%0A        if not user.is_member_of(domain):%0A            raise CommandError(%22%25s can't access %25s%22 %25 (user, domain))%0A%0A
     
@@ -1232,48 +1232,8 @@
 ))%0A%0A
-        config.couch_user_id = user._id%0A
     

fix and document case importer management command