from __future__ import absolute_import
from __future__ import unicode_literals

import zipfile
import csv

from django.test.testcases import TestCase
from custom.icds_reports.tasks import collect_inactive_dashboard_users
from custom.icds_reports.models.helper import IcdsFile
from corehq.apps.users.models import CommCareUser

class TestInactiveMobileUsers(TestCase):

    def test_get_inactive_users(self):
        IcdsFile.objects.filter(data_type='inactive_dashboard_users').all().delete()
        collect_inactive_dashboard_users()
        sync = IcdsFile.objects.filter(data_type='inactive_dashboard_users').order_by('-file_added').first()
        with sync.get_file_from_blobdb() as fileobj:
            zip = zipfile.ZipFile(fileobj, 'r')
            for zipped_file in zip.namelist():
                csv_reader = csv.reader(zip.open(zipped_file))
                data = list(csv_reader)

                self.assertEqual([['Username', 'Location', 'State']], data)

    def test_get_inactive_users_data_added(self):
        CommCareUser(domain='icds-cas', username='123.testing@icds-cas.commcare.org').save()
        CommCareUser(domain='icds-cas', username='234.testing@icds-cas.commcare.org').save()
        IcdsFile.objects.filter(data_type='inactive_dashboard_users').all().delete()
        collect_inactive_dashboard_users()
        sync = IcdsFile.objects.filter(data_type='inactive_dashboard_users').order_by('-file_added').first()
        with sync.get_file_from_blobdb() as fileobj:
            zip = zipfile.ZipFile(fileobj, 'r')
            for zipped_file in zip.namelist():
                csv_reader = csv.reader(zip.open(zipped_file), )
                data = list(csv_reader)
                sorted(data, key=lambda x: x[0])
                self.assertEqual([['Username', 'Location', 'State'],
                                  ['234.testing@icds-cas.commcare.org', '', ''],
                                  ['123.testing@icds-cas.commcare.org', '', '']
                                  ], data)

    def tearDown(self):
        CommCareUser.get_by_username('123.testing@icds-cas.commcare.org').delete()
        CommCareUser.get_by_username('234.testing@icds-cas.commcare.org').delete()

@@ -320,16 +320,17 @@
 reUser%0A%0A
+%0A
 class Te
@@ -2040,32 +2040,39 @@
 n(self):%0A       
+ user =
  CommCareUser.ge
@@ -2113,32 +2113,66 @@
 s.commcare.org')
+%0A        if user:%0A            user
 .delete()%0A      
@@ -2164,32 +2164,39 @@
 delete()%0A       
+ user =
  CommCareUser.ge
@@ -2245,16 +2245,50 @@
 re.org')
+%0A        if user:%0A            user
 .delete(

Correct test cases