from __future__ import absolute_import
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from corehq.blobs import get_blob_db
from corehq.form_processor.interfaces.dbaccessors import FormAccessors
from corehq.form_processor.models import XFormInstanceSQL
from corehq.util.log import with_progress_bar
from couchforms.const import ATTACHMENT_NAME
from couchforms.models import XFormInstance as CouchForm


class Command(BaseCommand):
    help = "Check if there is form.xml in all forms for a domain."

    def add_arguments(self, parser):
        parser.add_argument('domain', help='Domain to check.')
        parser.add_argument('file_name', help='Location to put the output.')

    def handle(self, domain, file_name, **options):
        blob_db = get_blob_db()
        form_db = FormAccessors(domain)
        form_ids = form_db.get_all_form_ids_in_domain()
        form_ids.append(form_db.get_all_form_ids_in_domain('XFormArchived'))

        with open(file_name, 'w') as open_file:
            for form in with_progress_bar(form_db.iter_forms(form_ids), len(form_ids)):
                if isinstance(form, CouchForm):
                    meta = form.blobs.get(ATTACHMENT_NAME)
                    if not meta or not blob_db.exists(
                            meta.id, form._blobdb_bucket()):  # pylint: disable=protected-access
                        open_file.write(form.form_id + "\n")
                elif isinstance(form, XFormInstanceSQL):
                    meta = form.get_attachment_meta(ATTACHMENT_NAME)
                    if not meta or not blob_db.exists(meta.blob_id, meta.blobdb_bucket()):
                        open_file.write(form.form_id + "\n")
                else:
                    raise Exception("not sure how we got here")

@@ -72,16 +72,27 @@
 iterals%0A
+import csv%0A
 from dja
@@ -1024,18 +1024,178 @@
  as 
-open_file:
+csv_file:%0A            field_names = %5B'domain', 'archived', 'form_id'%5D%0A            csv_writer = csv.DictWriter(csv_file, field_names)%0A            csv_writer.writeheader()%0A
 %0A   
@@ -1566,43 +1566,68 @@
     
-open_file.write(form.form_id + %22%5Cn%22
+self.write_row(csv_writer, domain, form.is_archived, form_id
 )%0A  
@@ -1869,43 +1869,68 @@
     
-open_file.write(form.form_id + %22%5Cn%22
+self.write_row(csv_writer, domain, form.is_archived, form_id
 )%0A  
@@ -2013,8 +2013,250 @@
  here%22)%0A
+%0A    @staticmethod%0A    def write_row(writer, domain, archived, form_id):%0A        properties = %7B%0A            'domain': domain,%0A            'archived': archived,%0A            'form_id': form_id,%0A        %7D%0A        csv_writer.writerow(properties)%0A

write as csv