from couchdbkit import Database
from dimagi.utils.couch.database import get_db
from django.core.management.base import LabelCommand, CommandError
from corehq.apps.domainsync.config import DocumentTransform, save


class Command(LabelCommand):
    help = "Copy any couch doc"
    args = '<sourcedb> <doc_id> (<domain>)'
    label = ""

    def handle(self, *args, **options):
        if len(args) < 2 or len(args) > 3:
            raise CommandError('Usage is copy_doc %s' % self.args)

        sourcedb = Database(args[0])
        doc_id = args[1]
        domain = args[2] if len(args) == 3 else None

        doc_json = sourcedb.get(doc_id)
        if domain:
            doc_json['domain'] = domain
        dt = DocumentTransform(doc_json, sourcedb)
        save(dt, get_db())

@@ -1,12 +1,22 @@
+import os%0A
 from couchdb
@@ -261,28 +261,212 @@
 p = 
+(
 %22Copy 
-any couch doc%22
+couch docs given as comma-separated list of IDs or path to file containing one ID per line. %22%0A            %22If domain is supplied save the doc with the given domain instead of its original domain.%22)
 %0A   
@@ -492,16 +492,30 @@
  %3Cdoc_id
+s_or_file_path
 %3E (%3Cdoma
@@ -738,16 +738,25 @@
   doc_id
+s_or_file
  = args%5B
@@ -812,16 +812,365 @@
 e None%0A%0A
+        if os.path.isfile(doc_ids_or_file):%0A            with open(doc_ids_or_file) as f:%0A                doc_ids = f.read().splitlines()%0A        else:%0A            doc_ids = doc_ids_or_file.split(',')%0A%0A        print %22Starting copy of %7B%7D docs%22.format(len(doc_ids))%0A        for doc_id in doc_ids:%0A            print 'Copying doc: %7B%7D'.format(doc_id)%0A    
         
@@ -1209,16 +1209,20 @@
         
+    
 if domai
@@ -1228,32 +1228,36 @@
 in:%0A            
+ 
+   
 doc_json%5B'domain
@@ -1268,16 +1268,20 @@
  domain%0A
+    
         
@@ -1323,16 +1323,20 @@
 urcedb)%0A
+    
         

support copying multiple docs in copy_doc command