import csv
from django.core.management.base import BaseCommand
from corehq.apps.locations.models import SQLLocation
from custom.enikshay.integrations.bets.repeaters import BETSLocationRepeater


class Command(BaseCommand):

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

    def handle(self, domain, **options):
        self.domain = domain
        filename = 'eNikshay_locations.csv'
        with open(filename, 'w') as f:
            writer = csv.writer(f)
            writer.writerow([
                'name',
                'site_code',
                'location_id',
                'doc_type',
                'domain',
                'external_id',
                'is_archived',
                'last_modified',
                'latitude',
                'longitude',
                # TODO exactly which metadata fields do they want? How do we
                # serialize the headers, metadata.is_test?
                # 'metadata',
                'location_type',
                'location_type_code',
                'parent_location_id',
                'parent_site_code',
                # They may also want ancestors_by_type, TBD
            ])
            loc_types = BETSLocationRepeater.location_types_to_forward
            for loc in (SQLLocation.active_objects
                        .filter(domain=domain, location_type__name__in=loc_types)
                        .prefetch_related('parent', 'location_type')):
                if loc.metadata.get('is_test') != "yes":
                    self.add_loc(loc, writer)
        print "Wrote to {}".format(filename)

    def add_loc(self, location, writer):
        writer.writerow([
            location.name,
            location.site_code,
            location.location_id,
            'Location',
            location.domain,
            location.external_id,
            location.is_archived,
            location.last_modified.isoformat(),
            float(location.latitude) if location.latitude else None,
            float(location.longitude) if location.longitude else None,
            # location.metadata,
            location.location_type.name,
            location.location_type.code,
            location.parent_location_id,
            location.parent.site_code,
            # They may also want ancestors_by_type, if so, use
            # custom.enikshay.integrations.bets.utils.get_bets_location_json
        ])

@@ -186,16 +186,91 @@
 epeater%0A
+from custom.enikshay.integrations.bets.utils import get_bets_location_json%0A
 %0A%0Aclass 
@@ -295,82 +295,44 @@
 d):%0A
-%0A
     
-def add_arguments(self, parser):%0A        parser.add_argument(
+field_names = %5B%0A        
 'domain'
 )%0A%0A 
@@ -331,118 +331,103 @@
 ain'
-)%0A
+,
 %0A    
-def handle(self, domain, **options):%0A        self.domain = domain%0A        filename = 'eNikshay_
+    'parent_site_code',%0A        'is_archived',%0A        'last_modified',%0A        '
 location
 s.cs
@@ -426,14 +426,13 @@
 tion
-s.csv'
+_id',
 %0A   
@@ -440,112 +440,94 @@
     
-with open(filename, 'w') as f:%0A            writer = csv.writer(f)%0A            writer.writerow(%5B%0A        
+'location_type',%0A        'location_type_code',%0A        'lineage',%0A        'doc_type',%0A
     
@@ -534,32 +534,24 @@
     'name',%0A
-        
         'sit
@@ -571,56 +571,117 @@
     
-        'location_id',%0A                'doc
+'longitude',%0A        'ancestors_by_type.ctd',%0A        'ancestors_by_type.sto',%0A        'ancestors_by
 _type
+.dto
 ',%0A 
@@ -679,32 +679,57 @@
 e.dto',%0A        
+'ancestors_by_type.cto',%0A
         'domain'
@@ -713,38 +713,40 @@
 .cto',%0A        '
-domain
+latitude
 ',%0A             
@@ -732,32 +732,39 @@
 itude',%0A        
+'_id',%0A
         'externa
@@ -778,36 +778,33 @@
         
-        'is_archived
+'metadata.is_test
 ',%0A     
@@ -806,38 +806,41 @@
         
-  
-      'last_modified
+'metadata.tests_available
 ',%0A     
@@ -846,441 +846,427 @@
     
- 
-       'latitude',%0A                'longitude',%0A                # TODO exactly which metadata fields do they want? How do we%0A                # serialize the headers, metadata.is_test?%0A                # 'metadata',%0A                'location_type',%0A                'location_type_code',%0A                'parent_location_id',%0A                'parent_site_code',%0A                # They may also want ancestors_by_type, TBD%0A            %5D
+'metadata.private_sector_org_id',%0A        'metadata.nikshay_code',%0A        'metadata.enikshay_enabled',%0A    %5D%0A%0A    def add_arguments(self, parser):%0A        parser.add_argument('domain')%0A%0A    def handle(self, domain, **options):%0A        self.domain = domain%0A        filename = 'eNikshay_locations.csv'%0A        with open(filename, 'w') as f:%0A            writer = csv.writer(f)%0A            writer.writerow(self.field_names
 )%0A  
@@ -1557,16 +1557,24 @@
      if 
+True or 
 loc.meta
@@ -1748,770 +1748,359 @@
     
-writer.writerow(%5B%0A            location.name,%0A            location.site_code,%0A            location.location_id,%0A            'Location',%0A            location.domain,%0A            location.external_id,%0A            location.is_archived,%0A            location.last_modified.isoformat(),%0A            float(location.latitude) if location.latitude else None,%0A            float(location.longitude) if location.longitude else None,%0A            # location.metadata,%0A            location.location_type.name,%0A            location.location_type.code,%0A            location.parent_location_id,%0A            location.parent.site_code,%0A            # They may also want ancestors_by_type, if so, use%0A            # custom.enikshay.integrations.bets.utils.get_bets_location_json%0A        %5D
+loc_data = get_bets_location_json(location)%0A%0A        def get_field(field):%0A            if field == 'lineage':%0A                return ''%0A            elif '.' in field:%0A                obj, key = field.split('.')%0A                return loc_data%5Bobj%5D.get(key, '')%0A            return loc_data%5Bfield%5D%0A%0A        writer.writerow(map(get_field, self.field_names)
 )%0A

Update format as per new spec