import csv

from django.core.management import BaseCommand

from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from corehq.util.log import with_progress_bar

from custom.enikshay.case_utils import get_person_case
from custom.enikshay.exceptions import ENikshayCaseNotFound


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('domain')
        parser.add_argument('case_type')
        parser.add_argument('log_file_name')
        parser.add_argument('case_ids', nargs='*')
        parser.add_argument('--commit', action='store_true')
        parser.add_argument('--deletion_id', dest='deletion_id', default='case_without_person')

    def handle(self, domain, case_type, log_file_name, case_ids, **options):
        commit = options['commit']
        deletion_id = options['deletion_id']

        if not case_ids:
            case_ids = self.get_case_ids(domain, case_type)

        with open(log_file_name, 'w') as log_file:
            logger = self.get_logger(log_file)
            for case_id in with_progress_bar(case_ids):
                if self.should_delete(domain, case_id):
                    self.delete_case(case_id, commit, deletion_id, domain, logger, case_type)

    @staticmethod
    def get_logger(log_file):
        logger = csv.writer(log_file)
        logger.writerow([
            'case_id', 'deletion_id', 'case_type',
            'date_form_created', 'date_form_modified', 'date_form_modified_non_system', 'last_user_to_modify',
        ])
        return logger

    @staticmethod
    def get_case_ids(domain, case_type):
        return CaseAccessors(domain).get_case_ids_in_domain(type=case_type)

    @staticmethod
    def should_delete(domain, case_id):
        try:
            return not get_person_case(domain, case_id)
        except ENikshayCaseNotFound:
            return True

    @staticmethod
    def delete_case(case_id, commit, deletion_id, domain, logger, case_type):
        date_form_modified_non_system = ''
        last_user_to_modify = ''

        case = CaseAccessors(domain).get_case(case_id)

        date_form_created = case.actions[0].form.received_on
        date_form_modified = case.actions[-1].form.received_on

        for action in reversed(case.actions):
            form = action.form
            if form.user_id:
                last_user_to_modify = form.user_id
                date_form_modified_non_system = form.received_on
                break


        logger.writerow([
            case_id, deletion_id, case_type,
            date_form_created, date_form_modified, date_form_modified_non_system, last_user_to_modify,
        ])
        if commit:
            CaseAccessors(domain).soft_delete_cases([case_id], deletion_id=deletion_id)

@@ -1965,24 +1965,280 @@
 _type):%0A    
+    _log_case_to_delete(case_id, deletion_id, domain, logger, case_type)%0A        if commit:%0A            CaseAccessors(domain).soft_delete_cases(%5Bcase_id%5D, deletion_id=deletion_id)%0A%0A%0Adef _log_case_to_delete(case_id, deletion_id, domain, logger, case_type):%0A
     date_for
@@ -2264,20 +2264,16 @@
 em = ''%0A
-    
     last
@@ -2294,28 +2294,24 @@
 y = ''%0A%0A    
-   
- 
 case = CaseA
@@ -2346,20 +2346,16 @@
 se_id)%0A%0A
-    
     date
@@ -2403,28 +2403,24 @@
 ived_on%0A    
-  
-  
 date_form_mo
@@ -2463,20 +2463,16 @@
 ved_on%0A%0A
-    
     for 
@@ -2513,20 +2513,16 @@
         
-    
 form = a
@@ -2540,20 +2540,16 @@
         
-   
- 
 if form.
@@ -2557,20 +2557,16 @@
 ser_id:%0A
-    
         
@@ -2608,36 +2608,32 @@
 _id%0A            
- 
-   
 date_form_modifi
@@ -2681,24 +2681,15 @@
     
-    
 break%0A%0A
-%0A    
     
@@ -2710,28 +2710,24 @@
 w(%5B%0A        
- 
-   
 case_id, del
@@ -2747,20 +2747,16 @@
 e_type,%0A
-    
         
@@ -2854,118 +2854,7 @@
     
-    %5D)%0A        if commit:%0A            CaseAccessors(domain).soft_delete_cases(%5Bcase_id%5D, deletion_id=deletion_id
+%5D
 )%0A

use helper function