from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from corehq.apps.locations.models import Location
from dimagi.utils.couch.database import get_db
import sys

class Command(BaseCommand):
    args = 'loc_uuid'
#    option_list = BaseCommand.option_list + (
#         )
    help = 'DELETE a location, all its sub-locations, and all associated data'

    def handle(self, *args, **options):
        try:
            loc_uuid = args[0]
        except IndexError:
            self.stderr.write('location uuid required\n')
            return

        try:
            loc = Location.get(loc_uuid)
            if not loc or loc.doc_type != 'Location':
                raise ValueError
        except Exception:
            self.stderr.write('doc [%s] does not appear to be a location\n' % loc_uuid)
            return

        self.db = get_db()

        startkey = [loc.domain] + loc.path
        locs = Location.view('locations/hierarchy', startkey=startkey, endkey=startkey + [{}], reduce=False, include_docs=True)
        for k in locs:
            self.delete_doc(k, loc)

        startkey = [loc.domain, loc._id]
        linked = self.db.view('locations/linked_docs', startkey=startkey, endkey=startkey + [{}], include_docs=True)
        for k in linked:
            self.delete_doc(k['doc'], loc)

    def delete_doc(self, doc, ref):
        id = doc['_id']

        def _get(field, default=None):
            try:
                return doc[field]
            except (KeyError, AttributeError):
                return default

        domain = _get('domain')
        domains = set(_get('domains', [])).union([domain] if domain else [])
        domain = domains.pop() if len(domains) == 1 else None

        path_fields = ['location_', 'path']
        for f in path_fields:
            path = _get(f)
            if path is not None:
                break

        if (not domain or ref.domain != domain) or (not path or path[:len(ref.path)] != ref.path):
            self.stderr.write('sanity check failed (%s)!\n' % id)
            return
        
        self.db.delete_doc(id)
        self.println('deleted %s' % id)

    def println(self, msg):
        self.stdout.write(msg + '\n')

@@ -1914,60 +1914,52 @@
  if 
-(not 
 domain 
-or ref.
+and 
 domain 
-!
+=
 = 
+ref.
 domain
-) or (not
+ and
  path 
-or
+and
  pat
@@ -1976,17 +1976,17 @@
 .path)%5D 
-!
+=
 = ref.pa
@@ -1987,17 +1987,16 @@
 ref.path
-)
 :%0A      
@@ -2010,84 +2010,69 @@
 elf.
-stderr.write('sanity check failed (%25s)!%5Cn' %25 id)%0A            return%0A        
+db.delete_doc(id)%0A            self.println('deleted %25s' %25 id)
 %0A   
@@ -2080,39 +2080,25 @@
     
-s
 el
-f.db.delete_doc(id)%0A
+se:%0A   
         
 self
@@ -2097,39 +2097,71 @@
     
+ 
 self.
-println('delet
+stderr.write('sanity check fail
 ed 
+(
 %25s
+)!%5Cn
 ' %25 id)
+%0A        
 %0A%0A  

make safety check logic more explicit