
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import User
from ideatree.models import UserProfile
from django.db import transaction
#import pdb
#import pprint


class Command(BaseCommand):

  def handle(self, *args, **options):
    try:
      # search free trial customers
      totalTrialDays = settings.FREE_ACCT_TRIALPERIOD_DAYS + settings.FREE_ACCT_GRACEPERIOD_DAYS
      # NOTE: Be sure this time zone matches what the database is set to, and that the database matches what the OS is set to.
      self.cutoffTime = (datetime.now(timezone.utc) - timedelta(days=totalTrialDays))
      freeusers = UserProfile.objects.filter(registerdate__lt = self.cutoffTime, accounttype=settings.FREE_ACCT)
      numchanged=0
      for fuserprofile in freeusers:
        with transaction.atomic():
          # FIXME: turn this line into a test of synchronicity between User and UserProfile tables.
          user = User.objects.get(pk=fuserprofile.user.id)
          if user.is_active ==True and  user.is_staff==False and user.is_superuser==False and user.username != settings.GUEST_USERNAME:
            numchanged += 1
            user.is_active = False
            user.save()
            # De-activate user
            self.stdout.write("Cutoff time:" + str(self.cutoffTime))
            self.stdout.write("Register date:" + str(fuserprofile.registerdate))
            self.stdout.write("User Profile id:" + str(fuserprofile.id))
            self.stdout.write("De-activated user " + str(user.id) + ": " + str(user.username) + "  " + str(user.email))
      if numchanged:
        self.stdout.write("Time now: " + str(datetime.now(timezone.utc)))
        self.stdout.write("The above customers, joining before " + str(self.cutoffTime.strftime('%Y-%m-%d %H:%M:%S%z')) + " UTC, have been marked inactive, the free trial of "+str(totalTrialDays)+ " days has ended.")

      self.stdout.write("\n\n")
    except CommandError as err:
      self.stdout.write("Error: (Possibly a User corresponding to UserProfile was not found.  " + str(err))
      self.stdout.write("\n\n")
    except Exception as err:
      self.stdout.write("Error: " + str(err))
      self.stdout.write("\n\n")

