from django.core.management.base import BaseCommand

from corehq.apps.hqcase.utils import bulk_update_cases
from corehq.util.log import with_progress_bar

from custom.enikshay.case_utils import get_all_episode_ids, iter_all_active_person_episode_cases


class ENikshayBatchCaseUpdaterCommand(BaseCommand):

    @property
    def updater(self):
        raise NotImplementedError("No updater class set")

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

    def handle(self, domain, **options):
        batch_size = 100
        updates = []
        errors = []

        case_ids = get_all_episode_ids(domain)
        cases = iter_all_active_person_episode_cases(domain, case_ids)

        for person, episode in with_progress_bar(cases, len(case_ids)):
            update_json = {}
            for updater in self.updaters:
                try:
                    update_json.update(updater(self.domain, episode).update_json())
                except Exception as e:
                    error = [episode.case_id, episode.domain, updater.__name__, e]
                    errors.append(error)
                    print "{}: {} - {}".format(*error)
            if update_json:
                updates.append((episode.case_id, update_json, False))
            if len(updates) >= batch_size:
                bulk_update_cases(domain, updates)
                updates = []

        if len(updates) > 0:
            bulk_update_cases(domain, updates)

@@ -1,12 +1,24 @@
+import csv%0A%0A
 from django.
@@ -784,86 +784,26 @@
 ids)
-):%0A            update_json = %7B%7D%0A            for updater in self.updaters:%0A    
+, oneline=False):%0A
     
@@ -827,28 +827,24 @@
             
-    
 update_json.
@@ -846,34 +846,37 @@
 json
-.update(updater(self.domai
+ = self.updater(domain, perso
 n, e
@@ -896,22 +896,17 @@
 e_json()
-)%0A    
+%0A
         
@@ -952,21 +952,39 @@
     
-    
 error
- = %5B
+s.append(%5Bperson.case_id, 
 epis
@@ -1016,124 +1016,37 @@
 in, 
-updater.__name__, e%5D%0A                    errors.append(error)%0A                    print %22%7B%7D: %7B%7D - %7B%7D%22.format(*error)
+e%5D)%0A                continue%0A
 %0A   
@@ -1320,28 +1320,448 @@
 date_cases(domain, updates)%0A
+%0A        self.write_errors(errors)%0A%0A    @property%0A    def log_filename(self):%0A        return %22%7B%7D_errors.csv%22.format(self.updater.__name__)%0A%0A    def write_errors(self, errors):%0A        if not errors:%0A            return None%0A%0A        with file(self.log_filename, 'w') as f:%0A            writer = csv.writer(f)%0A            writer.writerow(%5B'Person ID', 'Episode ID', 'Domain', 'Error'%5D)%0A            writer.writerows(errors)%0A

save errors to file