# Standard Libary
import datetime

# Django
from django.core.management.base import BaseCommand
from django.utils import timezone

from bhs.models import (
    Human,
    SMJoin,
    Structure,
)
from bhs.updaters import (
    update_or_create_group_from_structure,
    update_or_create_member_from_smjoin,
    update_or_create_person_from_human,
)


class Command(BaseCommand):
    help = "Command to sync with BHS database."

    def add_arguments(self, parser):
        parser.add_argument(
            '-a',
            '--all',
            action='store_true',
            dest='all',
            default=False,
            help='Update all groups.',
        )

        parser.add_argument(
            '-d',
            '--days',
            type=int,
            dest='days',
            nargs='?',
            const=2,
            help='Number of days to update.',
        )

    def handle(self, *args, **options):
        # sync persons
        self.stdout.write("Updating persons...")
        if options['all']:
            hs = Human.objects.all()
        else:
            now = timezone.now()
            cursor = now - datetime.timedelta(days=options['days'])
            hs = Human.objects.filter(
                updated_ts__gt=cursor,
            )
        total = hs.count()
        i = 0
        for h in hs:
            h.full_clean()
            i += 1
            update_or_create_person_from_human(h)
            self.stdout.write("{0}/{1}".format(i, total), ending='\r')
            self.stdout.flush()
        self.stdout.write("Updated {0} persons.".format(total))
        # Sync Groups
        self.stdout.write("Updating groups...")
        if options['all']:
            ss = Structure.objects.filter(
                kind__in=[
                    'quartet',
                    'chapter',
                ]
            )
        else:
            now = timezone.now()
            cursor = now - datetime.timedelta(days=options['days'])
            ss = Structure.objects.filter(
                kind__in=[
                    'quartet',
                    'chapter',
                ],
                updated_ts__gt=cursor,
            )
        total = ss.count()
        i = 0
        for s in ss:
            s.full_clean()
            i += 1
            update_or_create_group_from_structure(s)
            self.stdout.write("{0}/{1}".format(i, total), ending='\r')
            self.stdout.flush()
        self.stdout.write("Updated {0} groups.".format(total))

        # Sync Members
        self.stdout.write("Updating members...")
        if options['all']:
            js = SMJoin.objects.exclude(
                updated_ts=None,
            ).filter(
                structure__kind__in=[
                    'organization',
                    'quartet',
                    'chapter',
                ],
            ).order_by('updated_ts')
        else:
            now = timezone.now()
            cursor = now - datetime.timedelta(days=options['days'])
            js = SMJoin.objects.filter(
                structure__kind__in=[
                    'organization',
                    'quartet',
                    'chapter',
                ],
                updated_ts__gt=cursor,
            ).order_by('updated_ts')
        i = 0
        total = js.count()
        for j in js:
            j.full_clean()
            i += 1
            update_or_create_member_from_smjoin(j)
            self.stdout.write("{0}/{1}".format(i, total), ending='\r')
            self.stdout.flush()
        self.stdout.write("Updated {0} members.".format(total))
        self.stdout.write("Complete")

@@ -821,9 +821,9 @@
 nst=
-2
+1
 ,%0A  
@@ -885,178 +885,635 @@
     
-def handle(self, *args, **options):%0A        # sync persons%0A        self.stdout.write(%22Updating persons...%22)%0A        if options%5B'all'%5D:%0A            hs = Human.objects.all(
+    parser.add_argument(%0A            '-h',%0A            '--hours',%0A            type=int,%0A            dest='hours',%0A            nargs='?',%0A            const=1,%0A            help='Number of hours to update.',%0A        )%0A%0A    def handle(self, *args, **options):%0A        # sync persons%0A        self.stdout.write(%22Updating persons...%22)%0A        if options%5B'all'%5D:%0A            hs = Human.objects.all()%0A        elif options%5B'hours'%5D:%0A            now = timezone.now()%0A            cursor = now - datetime.timedelta(hours=options%5B'hours'%5D, minutes=5)%0A            hs = Human.objects.filter(%0A                updated_ts__gt=cursor,%0A            
 )%0A  
@@ -1615,32 +1615,41 @@
 =options%5B'days'%5D
+, hours=1
 )%0A            hs
@@ -2304,32 +2304,381 @@
 %5D%0A            )%0A
+        elif options%5B'hours'%5D:%0A            now = timezone.now()%0A            cursor = now - datetime.timedelta(hours=options%5B'hours'%5D, minutes=5)%0A            ss = Structure.objects.filter(%0A                kind__in=%5B%0A                    'quartet',%0A                    'chapter',%0A                %5D,%0A                updated_ts__gt=cursor,%0A            )%0A
         else:%0A  
@@ -2766,32 +2766,41 @@
 =options%5B'days'%5D
+, hours=1
 )%0A            ss
@@ -3696,32 +3696,448 @@
 y('updated_ts')%0A
+        elif options%5B'hours'%5D:%0A            now = timezone.now()%0A            cursor = now - datetime.timedelta(hours=options%5B'hours'%5D, minutes=5)%0A            js = SMJoin.objects.filter(%0A                structure__kind__in=%5B%0A                    'organization',%0A                    'quartet',%0A                    'chapter',%0A                %5D,%0A                updated_ts__gt=cursor,%0A            ).order_by('updated_ts')%0A
         else:%0A  

Update sync script to include hours